我正在做自定义授权属性。
想在类和控制器级别使用此属性。
此代码适用于方法级别
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();
}
}
抱歉英语不好。
答案 0 :(得分:0)
最后我不需要反射或任何花哨的东西,在AuthorizeAttribute我有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);
}
}