C# 我可以从派生属性访问控制器/动作/动词吗?
作为帮助我了解与MVC相关的成员资格模型细节的理论练习,我想弄清楚我是否可以从外部资源加载权限,对于我的原型,我有一个平面文件,其中包含如下列表:C# 我可以从派生属性访问控制器/动作/动词吗?,c#,.net,asp.net-mvc,C#,.net,Asp.net Mvc,作为帮助我了解与MVC相关的成员资格模型细节的理论练习,我想弄清楚我是否可以从外部资源加载权限,对于我的原型,我有一个平面文件,其中包含如下列表: Controller1,Method1,Get,Anonymous Controller1,Method1,Post,User,Administrator Controller2,Method1,Get,Administrator Controller2,Method1,Post,Administrator Controller2,Method2,G
Controller1,Method1,Get,Anonymous
Controller1,Method1,Post,User,Administrator
Controller2,Method1,Get,Administrator
Controller2,Method1,Post,Administrator
Controller2,Method2,Get,User,Editor,Administrator
Controller2,Method2,Post,Editor,Administrator
我可以使用正则表达式对其进行分析,以提供对每个控制器/动作/动词组合具有权限的角色列表
我有我的控制器操作:
[CustomAuthorize]
public ActionResult Index()
{
/* Do stuff */
}
我还有我的自定义授权组件:
public class CustomAuthorize : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
/* How do I access which Controller/Action/Verb fired this? */
}
}
为了能够动态确定哪些角色可以访问此控制器/操作/谓词,我需要能够确定哪个控制器/操作/谓词称为CustomAuthorize属性
我知道我可以像这样向类中添加属性:
public class CustomAuthorize : AuthorizeAttribute
{
public string Controller { get; set; }
public string Action { get; set; }
public string Verb { get; set; }
}
然后使用以下命令调用我的属性:
[CustomAuthorize(Controller="Home",Action="Index",Verb="Get")]
public ActionResult Index()
{
}
但这似乎是一个维护头痛。如果我可以使用[Authorize]
并让我的CustomAuthorize.AuthorizeCore方法确定哪个控制器/动作/动词在AuthorizeCore方法中引用它,那就太好了
这可能吗?如果是这样的话,有人能告诉我如何实现这一点的信息的正确方向吗?您可能想看看重写授权。它获取一个AuthorizationContext参数,该参数引用控制器和RoutedData。不过,请看一下标准属性的作用,特别是在缓存方面。您可能会在我写的一篇关于的文章中找到一些想法。尝试覆盖授权
public class TestAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
string controllerName = filterContext.RouteData["controller"];
string actionName = filterContext.RouteData["action"];
string verb = filterContext.HttpContext.Request.HttpMethod;
// .. do your processing
// if fail...
filterContext.Result = new HttpUnauthorizedResult();
base.OnAuthorization(filterContext);
}
}
我读过你关于定制授权的帖子。提供有用信息的看来你的建议应该能奏效。不过,如果没有tvanfosson上面提到的关于缓存的警告,这有点危险。很遗憾,我不能同时接受这两个答案。。。它们都很有用,信息丰富,都做了我想要的。@Craig-作为一个理论练习,这给出了我想要的信息,方法的前三行就是我想要的。我可以用我的AuthorizeCore()方法处理剩下的问题,正如TV的回答所暗示的那样。