Passing as a parameter a generic type in an attribute in the .NET MVC

1

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?

    
asked by anonymous 29.06.2016 / 17:18

1 answer

0

You can pass a type to your attribute:

[Authorized(typeof(User))]

Your attribute would have to change a bit:

public class Authorized : ActionFilterAttribute
{
    private Type guardType;

    ...
}

Calling the check method I would do as follows:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    if(Auth.Check(guardType))
        ...
}

Check must have a signature like this:

public bool Check(Type tipo) { ... }
    
03.10.2016 / 22:33