在所有的控制器动作强制行为过滤器(C#/ ASP.NET MVC)
-
20-09-2019 - |
题
我提出了一个新的动作过滤器(属性,类似于[授权]),该授权访问基于会话值的控制器的动作。不过,我基本上装饰与属性(除了极少数例外),我所有的控制器动作。
所以,我认为这将是最好有一个行为过滤器的总是的执行的的情况除外的,我附上一个[ExemptFromAuthorize]属性控制器行动? (也许通过继承到我自己的控制器类?)
我怎样才能做到这一点?
解决方案
与 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 -
http://www.codeproject.com/KB/web-security/ AuthorizeWithExemptions.aspx
在这篇文章中,我会向您提供的方式,所有的动作被固定,除了那些定义为不安全确保ASP.NET MVC应用程序控制器的解决方案。
从代码剪断:
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);
}
我明白这个问题是非常过时的,但无论如何..如果你想申请过滤器,所有操作只需添加以下行到Global.asax中:
protected void Application_Start()
{
// your code here and then
RegisterGlobalFilters(GlobalFilters.Filters);
}
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new MyActionFilterAttribute());
}
和行动过滤器,你可以只检查行动有以下方式的任何其他属性:
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();
}
}
我不知道如何排除从一个类级别属性的具体方法。也许使用一个单独的控制器,用于身份认证的请求?
有关任何人在2013+读这篇文章,MVC4现在支持使用 [使用AllowAnonymous]
可以把授权控制器上,然后允许匿名上 任何功能,你不想授权。
示例:
[授权] 公共类的HomeController:控制器{
[AllowAnonymous] public ActionResult Index() { }
}
会与自定义[MyAuthorize]过滤器这一工作或者它仅与工作[授权]
有关任何人在2013+读这篇文章,MVC4现在支持使用[AllowAnonymous]
的
您可以将控制器上的授权,然后允许匿名你不想授权任何功能。
示例:
[Authorize]
public class HomeController : Controller
{
[AllowAnonymous]
public ActionResult Index()
{
}
}