在所有的控制器动作强制行为过滤器(C#/ ASP.NET MVC) [英] Enforce Action Filter on all Controller Actions (C# / ASP.NET MVC)

查看:643
本文介绍了在所有的控制器动作强制行为过滤器(C#/ ASP.NET MVC)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个新的动作过滤器(属性,类似于[授权])的授权访问基于会话值控制器动作。不过,我基本上装饰与属性的(除了极少数例外),我所有的控制器动作。

I made a new action filter (attribute, similar to [Authorize]) which authorizes access to a controller action based on a session value. However, I'm basically decorating all my controller actions with that attribute (with the exception of very few).

所以,我认为这将是最好有一个行为过滤器的总是的执行的情况除外的,其中附上一份[ExemptFromAuthorize]属性到一个控制器行动? (也许通过继承我自己的Controller类?)

So, I thought it would be better to have that Action Filter always executed except in cases where I attach an [ExemptFromAuthorize] attribute to a controller action? (Maybe via inheriting to my own Controller class?)

我怎样才能做到这一点?

How can I do this?

推荐答案

与运行<一个href=\"http://stackoverflow.com/questions/1343652/enforce-action-filter-on-all-controller-actions-c-asp-net-mvc/1343726#1343726\">jeef3's答案,我想出了这个。它可以使用更多的错误检查和鲁棒性像多分隔措施,但总的思想工作。

Running with jeef3's answer, I came up with this. It could use more error checking and robustness like multiple delimited actions, but the general idea works.

在特定的情况下,可以测试会话值,并决定返回了授权也。

In your specific case, you could test for the session value and decide to return out of the authorization also.

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
...

这篇关于在所有的控制器动作强制行为过滤器(C#/ ASP.NET MVC)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆