[英]Don't apply ActionFilterAttribute to a specific route?
I have a MvC .Net web application and am applying an action filter attribute to all routes. 我有一个MvC .Net Web应用程序,并将动作过滤器属性应用于所有路由。 How do I configure it so that this filter is NOT applied for a specific route (ie "/api/ignore") I specify in WebApiConfig.cs? 如何配置它以使此过滤器不应用于我在WebApiConfig.cs中指定的特定路由(即“/ api / ignore”)?
In my Globax.asax.cs, I have these 2 lines in Application_Start() so this filter is called. 在我的Globax.asax.cs中,我在Application_Start()中有这两行,因此调用此过滤器。
ISessionFilter sessionFilter = (ISessionFilter) DependencyResolver.Current.GetService<ISessionFilter>();
GlobalFilters.Filters.Add(sessionFilter);
This is my filter: 这是我的过滤器:
public class SessionFilter : System.Web.Mvc.ActionFilterAttribute, System.Web.Mvc.IActionFilter, ISessionFilter
{
public SessionFilter()
{
}
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
{
//logic here
}
}
Is there a clean way to do this? 有干净的方法吗? Do I need to hard code the route to ignore in my filter class (I'd prefer not to do this) 我是否需要在我的过滤器类中硬编码要忽略的路径(我不想这样做)
In Rails there's something called :skip_before_filter... Unfortunately, in .NET you need to do something like this (basically make a dummy attribute that when you put on an action, depending on some condition of your liking, stops that action's execution): 在Rails中有一些叫做:skip_before_filter ...不幸的是,在.NET中你需要做这样的事情(基本上做一个虚拟属性,当你做一个动作时,根据你喜欢的某些条件,停止该动作的执行):
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class HanlleyDisable : Attribute { }
public class SessionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
bool disabled = filterContext.ActionDescriptor.IsDefined(typeof(HanlleyDisable ), true) ||
filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(HanlleyDisable), true);
if (disabled)
return;
// action filter logic here...
}
}
class FooController {
[HanlleyDisable]
MyMethod() { ... }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.