In another question I made here I had to modify my authentication class to return the values of the user model and the type of authenticated user, eg admins, users, clients , so I had to implement a generic type of the call, and a new interface. But in conjunction with the authentication class I use a ActionFilterAttribute
to allow or deny access to the routes actions, the declaration is:
[Authorized("users")]
public ActionResult Index()
{
...
But because it is an attribute I am not able to implement a generic type so that I can use the authentication class to do the necessary checks, as in the following example, which does not 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())
...
}
}
Then I tried to start the type through a string as 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 make the check with the method Check()
that receives as a parameter T the return of the Guard()
method, which receives a string and returns a type.
Auth.Guard(string guard_name).Check()
The Guard
method of class Auth
looks like this:
public static T Guard<T>(string guard_name) where T : class, IAuth
{
return (T)Activator.CreateInstance(Type.GetType(guard_name));
}
And also did not work because the Auth.Guard()
method does not only accept a string, it is also necessary to pass as a reference a type to pass as T
parameter to other methods as Auth.Check()
, however inside the Autorized
filter % I can not pass this reference.
I tried this way and it also does not work because T
is invalid:
public static T Guard(string guard_name)
{
return (T)Activator.CreateInstance(Type.GetType(guard_name));
}
How can I resolve?