Ale*_*lex 12 .net c# asp.net-mvc action-filter controller-action
我创建了一个新的动作过滤器(属性,类似于[Authorize]),它根据会话值授权访问控制器动作.但是,我基本上用该属性装饰我的所有控制器动作(除了极少数).
所以,我认为除了在将[ExemptFromAuthorize]属性附加到控制器动作的情况下,总是执行Action Filter会更好吗?(也许通过继承我自己的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);
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
[AuthorizeWithExemptions(Roles="admin", ExemptAction="Index")]
public class AdminController : Controller
...
Run Code Online (Sandbox Code Playgroud)
查看我在codeproject上的文章 -
http://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);
}
Run Code Online (Sandbox Code Playgroud)
我理解这个问题已经过时但无论如何..如果你想对所有操作应用过滤器,只需在Global.asax中添加以下行:
protected void Application_Start()
{
// your code here and then
RegisterGlobalFilters(GlobalFilters.Filters);
}
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new MyActionFilterAttribute());
}
Run Code Online (Sandbox Code Playgroud)
在动作过滤器中,您可以通过以下方式检查动作是否具有任何其他属性:
public void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.ActionDescriptor.IsDefined(typeof(AnotherActionAttribute), false))
{
// do what you want to do
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12187 次 |
| 最近记录: |