ASP.NET MVC:在基控制器类忽略自定义属性 [英] ASP.NET MVC: Ignore custom attribute in a base controller class
问题描述
我有一些在我的项目控制器,所有从控制器我命名BaseController继承的。我写了我应用到整个BaseController类的自定义属性,使每一个动作在我的任何控制器运行时,该属性将首先运行。
I have a number of Controllers in my project that all inherit from a controller I've named BaseController. I wrote a custom attribute that I applied to the entire BaseController class, so that each time an action runs in any of my controllers, that attribute will run first.
问题是,我有一对夫妇,我想忽略属性控制器动作,但我不知道该怎么做。
The problem is that I have a couple of controller actions that I'd like to ignore that attribute, but I don't know how to do it.
谁能帮助?我使用MVC 1。
Can anyone help? I'm using MVC 1.
感谢。
推荐答案
我有这样的事情同样需要,并发现,通过创建授权过滤器(执行/从 FilterAttribute,个IAuthorizationFilter <导出/ code>),而不是一个常规动作过滤器(从派生
ActionFilterAttribute
),并设置继承= TRUE
和的AllowMultiple = FALSE
的属性,它只会在适当的位置运行一次。
I had a similar need for something like this and found that by creating an authorization filter (implementing/deriving from FilterAttribute, IAuthorizationFilter
) rather than a regular action filter (deriving from ActionFilterAttribute
), and setting Inherited=true
and AllowMultiple=false
on the attribute, that it would only run once at the appropriate spot.
这意味着我能层叠我滤镜从基本控制器(站点范围的默认值)下来,派生控制器(例如AdminController或其他),或者甚至下降到一个单独的操作方法进一步。
This means I am able to "cascade" my filter down from a base controller (the site-wide default), to a derived controller (for example the AdminController or whatever), or even further down to an individual action method.
例如,
[AttributeUsage(AttributeTargets.Class|AttributeTargets.Method, Inherited=true, AllowMultiple=false)]
public class MyCustomAttribute : FilterAttribute, IAuthorizationFilter
{
private MyCustomMode _Mode;
public MyCustomAttribute(MyCustomMode mode)
{
_Mode = mode;
}
public virtual void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
// run my own logic here.
// set the filterContext.Result to anything non-null (such as
// a RedirectResult?) to skip the action method's execution.
//
//
}
}
public enum MyCustomMode
{
Enforce,
Ignore
}
然后使用它,我可以把它应用到我的超级控制器,
And then to use it, I can apply it to my super-controller,
[MyCustomAttribute(Ignore)]
public class BaseController : Controller
{
}
和我可以改变/重写它针对特定的控制器,甚至是具体行动!
And I can change/override it for specific controllers, or even for specific actions!
[MyCustomAttribute(Enforce)]
public class AdministrationController : BaseController
{
public ActionResult Index()
{
}
[MyCustomAttribute(Ignore)]
public ActionResult SomeBasicPageSuchAsAHelpDocument()
{
}
}
这让我为关闭过滤器的具体情况,同时仍然能够将它应用为无论是整个控制器或整个应用程序在默认的。
This allowed me to "turn off" the filter for specific cases, while still being able to apply it as a default on either the whole controller or whole application.
祝你好运!
这篇关于ASP.NET MVC:在基控制器类忽略自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!