对所有控制器操作强制执行操作筛选(C#/ ASP.NET MVC)
我创建了一个新的动作filter(属性,类似于[Authorize]),它根据会话值授权访问控制器动作。 但是,我基本上用该属性装饰我的所有控制器动作(除了极少数)。
所以,我认为除了在将[ExemptFromAuthorize]属性附加到控制器动作的情况下, 总是执行Action Filter会更好吗? (也许通过inheritance我自己的Controller类?)
我怎样才能做到这一点?
按照jeef3的回答,我想出了这个。 它可以使用更多错误检查和稳健性,如多个分隔操作,但总体思路有效。
在您的特定情况下,您可以测试会话值并决定退出授权。
public class AuthorizeWithExemptionsAttribute : AuthorizeAttribute { public string Exemption { get; set; } public override void OnAuthorization(AuthorizationContext filterContext) { if (filterContext.RouteData.GetRequiredString("action") == Exemption) return; base.OnAuthorization(filterContext); } }
用法:
[AuthorizeWithExemptions(Roles="admin", ExemptAction="Index")] public class AdminController : Controller ...
看看我在codeproject上的文章 –
https://www.codeproject.com/KB/web-security/AuthorizeWithExemptions.aspx
在本文中,我将为您提供一种保护ASP.NET MVC应用程序控制器的解决方案,除了您定义为不安全的操作外,所有操作都是安全的。
代码中的snipper:
public override void OnAuthorization(AuthorizationContext filterContext) { ActionDescriptor action = filterContext.ActionDescriptor; bool IsUnsecured = action.GetCustomAttributes( typeof(UnsecuredActionAttribute), true).Count() > 0; //If doesn't have UnsecuredActionAttribute - then do the authorization filterContext.HttpContext.SkipAuthorization = IsUnsecured; base.OnAuthorization(filterContext); }
我理解这个问题已经过时但无论如何..如果您希望对所有操作应用filter,只需在Global.asax中添加以下行:
protected void Application_Start() { // your code here and then RegisterGlobalFilters(GlobalFilters.Filters); } public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new MyActionFilterAttribute()); }
在动作filter中,您可以通过以下方式检查动作是否具有任何其他属性:
public void OnActionExecuting(ActionExecutingContext filterContext) { if (filterContext.ActionDescriptor.IsDefined(typeof(AnotherActionAttribute), false)) { // do what you want to do } }
也许尝试在您的第一个属性中添加一个Except
属性?
[MyAuthenticate(Exempt="View")] public class MyController : Controller { public ActionResult Edit() { // Protected } public ActionResult View() { // Accessible by all } }
您可以将该属性添加到类中,以使其适用于该类中的所有方法
[Authenticate] public class AccountController : Controller { public ActionResult Index() { return View(); } }
我不知道如何从类级属性中排除特定方法。 也许对未经身份validation的请求使用单独的控制器?
对于在2013年以上阅读此内容的任何人,MVC4现在支持使用[AllowAnonymous]
您可以将Authorize放在控制器上,然后在您不想授权的任何function上允许匿名。
例:
[授权]公共类HomeController:Controller {
[AllowAnonymous] public ActionResult Index() { }
}
这是否适用于自定义[MyAuthorize]filter,或仅适用于[授权]
对于在2013年以上阅读此内容的任何人,MVC4现在支持使用[AllowAnonymous]
您可以将Authorize放在控制器上,然后在您不想授权的任何function上允许匿名。
例:
上述就是C#学习教程:对所有控制器操作强制执行操作筛选(C#/ ASP.NET MVC)分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
[Authorize] public class HomeController : Controller { [AllowAnonymous] public ActionResult Index() { } }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/955759.html