如何有选择地禁用 ASP.Net MVC 中的全局过滤器 [英] How to disable a global filter in ASP.Net MVC selectively

查看:20
本文介绍了如何有选择地禁用 ASP.Net MVC 中的全局过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经为我打开和关闭 NHibernate 会话的所有控制器操作设置了一个全局过滤器.这些操作中的 95% 需要一些数据库访问权限,但 5% 不需要.有没有什么简单的方法可以为那 5% 禁用这个全局过滤器.我可以反过来,只装饰需要数据库的操作,但这会做更多的工作.

I have set up a global filter for all my controller actions in which I open and close NHibernate sessions. 95% of these action need some database access, but 5% don't. Is there any easy way to disable this global filter for those 5%. I could go the other way round and decorate only the actions that need the database, but that would be far more work.

推荐答案

你可以写一个标记属性:

You could write a marker attribute:

public class SkipMyGlobalActionFilterAttribute : Attribute
{
}

然后在您的全局操作过滤器中测试操作上是否存在此标记:

and then in your global action filter test for the presence of this marker on the action:

public class MyGlobalActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(SkipMyGlobalActionFilterAttribute), false).Any())
        {
            return;
        }

        // here do whatever you were intending to do
    }
}

然后如果你想从全局过滤器中排除一些动作,只需用标记属性装饰它:

and then if you want to exclude some action from the global filter simply decorate it with the marker attribute:

[SkipMyGlobalActionFilter]
public ActionResult Index()
{
    return View();
}

这篇关于如何有选择地禁用 ASP.Net MVC 中的全局过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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