gpt4 book ai didi

asp.net-mvc - 如何有选择地禁用 ASP.Net MVC 中的全局过滤器

转载 作者:行者123 更新时间:2023-12-03 05:21:24 25 4
gpt4 key购买 nike

我已经为我打开和关闭 NHibernate session 的所有 Controller 操作设置了一个全局过滤器。其中 95% 的操作需要一些数据库访问,但 5% 不需要。有什么简单的方法可以禁用这 5% 的全局过滤器吗?我可以采取相反的方式,只装饰需要数据库的操作,但这会需要更多工作。

最佳答案

您可以编写标记属性:

public class SkipMyGlobalActionFilterAttribute : Attribute
{
}

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

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

然后,如果您想从全局过滤器中排除某些操作,只需使用标记属性来装饰它即可:

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

关于asp.net-mvc - 如何有选择地禁用 ASP.Net MVC 中的全局过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9953760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com