在属性方法中获取带有贡品的类中的类名

本文关键字:属性 方法 获取 | 更新日期: 2023-09-27 17:55:44

我正在做一个自定义授权属性。

希望在类和控制器级别使用此属性。

此代码在方法级别工作

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    public CustomAuthorizeAttribute([CallerMemberName] string callerName = null)
    {
        CallerName = callerName;
    }
    public string CallerName { get; set; }
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext.User.IsInRole("Admin"))
            return true;
        ...
        if (CallerName == something)
        {
            do this
        }
        ...
        return base.AuthorizeCore(httpContext);
    }
}

诸如此类

    [CustomAuthorize()]
    public ActionResult Index()
    {
        return View();
    }

但是我想在控制器中全局使用

[CustomAuthorize()]
public class UsuariosController : Controller
{
    SalusDbContext db = new SalusDbContext();

    // GET: Usuarios
    public ActionResult Index()
    {
        return View();
    }
}

对不起,英语不好。

在属性方法中获取带有贡品的类中的类名

最后我不需要反射或任何花哨的东西,在授权属性中我有 httpContext,有了这个我可以得到路由、控制器和操作名称。

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var routeValues = httpContext.Request.RequestContext.RouteData.Values;
        if (httpContext.User.IsInRole("Admin"))
            return true;
        var controller = routeValues["Controller"];
        var action = routeValues["Action"];
        return base.AuthorizeCore(httpContext);
    }
}