1
In another question I asked here I had to modify my authentication class to return the values of the model referring to the user and the authenticated user type, for example, admins, users, clients, so I had to implement a generic type to the call, and a new interface. But in conjunction with the authentication class I use a ActionFilterAttribute
to allow or deny access to Routes, the statement is:
[Authorized("users")]
public ActionResult Index()
{
...
But because it’s an attribute I’m not able to implement a generic type so I can use the authentication class to do the necessary checks, as in the following example, which doesn’t work, but is only to describe the need:
Statement:
[Authorized<users>]
public ActionResult Index()
{
...
Filter:
public class Authorized : ActionFilterAttribute
{
private T guard;
public Authorized<T>() where T : class, IAuth
{
this.guard = guard;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if(Auth.<T>Check())
...
}
}
So I tried to start the type through a string like in the first example, the filter class is:
public class Authorized : ActionFilterAttribute
{
private string guard_name;
public Authorized(string guard_name)
{
this.guard_name = guard_name;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if(Auth.Guard(guard_name).Check())
...
}
}
Notice that in the execution I do the verification with the method Check()
which receives as parameter T the return of the method Guard()
, that takes a string and returns a type.
Auth.Guard(string guard_name).Check()
The method Guard
class Auth
gets like this:
public static T Guard<T>(string guard_name) where T : class, IAuth
{
return (T)Activator.CreateInstance(Type.GetType(guard_name));
}
And it didn’t work either because the method Auth.Guard()
not only accepts a string, it is necessary to also be passed as reference a type to pass as T
parameter for other methods like Auth.Check()
, but inside the filter Autorized
I have no way to pass this reference.
I tried this way and it doesn’t work either because the T
is invalid:
public static T Guard(string guard_name)
{
return (T)Activator.CreateInstance(Type.GetType(guard_name));
}
How can I solve?