How to create a method that takes only one string parameter and returns a generic type? .NET MVC

1

How could I create a method that does not need to receive a type as a parameter, only a string , but would return a type?

As for example:

public static T Guard(string guard_name) where T : class, IAuth
{
    return (T)Activator.CreateInstance(Type.GetType(guard_name));
}

Instead of:

public static T Guard<T>(string guard_name) where T : class, IAuth
{
    return (T)Activator.CreateInstance(Type.GetType(guard_name));
}

Then the call would look like this: Auth.Guard("users") instead of Auth.Guard<users>() .

I need a method that only receives a string and not a type because I'm working with a class ActionFilterAttribute that the statement is [Autorized(string guard_name)] and therefore I can not use a type at that time. I've already tried variations like [Autorized<users>] for example, but because it was an attribute I could not do it.

Is it possible?

    
asked by anonymous 30.06.2016 / 15:19

1 answer

3

This approach is not good at all. You are choosing to resolve a string to a type in an authorization attribute.

The correct one would be to specify a type in the authorization attribute. Something like:

public class MeuAuthorizeAttribute : AuthorizeAttribute
{
    public Type TipoClasse { get; set; }
    private SeuProjetoContexto contexto = new SeuProjetoContexto();

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var dbSet = contexto.Set(TipoClasse);
        /* Insira aqui sua lógica */
    }
}

Usage:

[MeuAuthorize(typeof(MeuModel))]
    
30.06.2016 / 15:44