【问题标题】:ASP.NET MVC: Ignore custom attribute in a base controller classASP.NET MVC:忽略基本控制器类中的自定义属性
【发布时间】:2011-05-22 09:22:47
【问题描述】:

我的项目中有许多控制器都继承自我命名为 BaseController 的控制器。我编写了一个应用到整个 BaseController 类的自定义属性,这样每次在我的任何控制器中运行一个操作时,该属性都会首先运行。

问题是我有几个控制器操作我想忽略该属性,但我不知道该怎么做。

有人可以帮忙吗?我正在使用 MVC 1。

谢谢。

【问题讨论】:

  • 你能发布你的属性吗?它会阻止动作被击中吗?
  • 出于专有数据的原因,我宁愿不发布该属性,但是可以,它可能会将用户重定向到登录页面,而不是允许点击该操作。

标签: asp.net-mvc inheritance custom-attributes base-class


【解决方案1】:

在您的自定义属性中,您可以像这样添加这个 ShouldRun() 检查:

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (ShouldRun(filterContext))
        {
            // proceed with your code
        }
    }

    private bool ShouldRun(ActionExecutingContext filterContext)
    {
        var ignoreAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(IgnoreMyCustomAttribute), false);
        if (ignoreAttributes.Length > 0)
            return false;

        return true;
    }

ShouldRun() 仅检查您的操作中是否存在“IgnoreMyCustomAttribute”。如果它在那里,那么您的自定义属性将不会做任何事情。

您现在要创建一个简单的 IgnoreMyCustomAttribute,它什么都不做:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class IgnoreMyCustomAttribute: ActionFilterAttribute
{
}

当你用 [IgnoreMyCustom] 装饰你的控制器动作时,MyCustomAttribute 不会做任何事情。例如:

[IgnoreMyCustom]
public ViewResult MyAction() {
}

【讨论】:

    【解决方案2】:

    我对类似的东西也有类似的需求,并发现通过创建授权过滤器(实现/派生自 FilterAttribute, IAuthorizationFilter)而不是常规操作过滤器(派生自 ActionFilterAttribute),并设置 Inherited=true 和 @ 987654325@ 在属性上,它只会在适当的位置运行一次。

    这意味着我可以将过滤器从基本控制器(站点范围的默认设置)“级联”到派生控制器(例如 AdminController 或其他),甚至进一步下降到单个操作方法。

    例如,

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

    然后要使用它,我可以将它应用到我的超级控制器,

    [MyCustomAttribute(Ignore)]
    public class BaseController : Controller
    {
    }
    

    而且我可以为特定控制器甚至特定操作更改/覆盖它!

    [MyCustomAttribute(Enforce)]
    public class AdministrationController : BaseController
    {
        public ActionResult Index()
        {
        }
    
        [MyCustomAttribute(Ignore)] 
        public ActionResult SomeBasicPageSuchAsAHelpDocument()
        {
        }
    }
    

    这让我可以针对特定情况“关闭”过滤器,同时仍然可以将其作为默认值应用到整个控制器或整个应用程序上。

    祝你好运!

    【讨论】:

    【解决方案3】:

    我不确定在这种情况下是否有一种简单的方法可以删除属性。但是我为一个项目做了类似的事情,我所做的只是在少数情况下我不想让我的属性运行,所以我做了两个属性。

    我的第一个属性已应用到我的基本控制器,但它知道第二个属性的存在,通过实现第二个属性,我可以禁用基类上的属性运行。

    不确定这是否是最好的解决方案,但它对我有用。

    这已应用于基本控制器:

    /// <summary>
    /// This is used to force the schema to HTTP is it is HTTPS.
    /// RequireHttpsAttribute or OptionalHttpsAttribute takes precedence if used.
    /// </summary>
    public class RequireHttpAttribute : FilterAttribute, IAuthorizationFilter
    {
        public virtual void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
                throw new ArgumentNullException("filterContext");
    
            if (filterContext.HttpContext.Request.IsSecureConnection)
            {
                object[] attributes = filterContext.ActionDescriptor.GetCustomAttributes(true);
                if (!attributes.Any(a => a is RequireHttpsAttribute || a is OptionalHttpsAttribute))
                {
                    HandleHttpsRequest(filterContext);
                }
            }
        }
    
        protected virtual void HandleHttpsRequest(AuthorizationContext filterContext)
        {
            //  only redirect for GET method, otherwise browser may not propogate the verb and request body correctly
            if (!string.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
                throw new InvalidOperationException(MvcResources.RequireHttpAttribute_MustNotUseSsl);
    
            //  redirect to HTTP version
            string url = "http://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
            filterContext.Result = new RedirectResult(url);
        }
    }
    

    像这样:

    [RequireHttp]
    public abstract class Controller : System.Web.Mvc.Controller
    {
    }
    

    然后我可以使用实际上是一个虚拟属性来禁用它。

    /// <summary>
    /// This attribute allows the action to be server on HTTP and HTTPS but neither is enforce.
    /// RequireHttpsAttribute takes precedence if used.
    /// </summary>
    public class OptionalHttpsAttribute : FilterAttribute
    {
        // This is deliberately empty, the attribute is used by RequireHttpAttribute to stop it changing schema to HTTP
    }
    

    像这样:

        [OptionalHttps]
        public ActionResult OptionalHttps()
        {
            return View();
        }
    

    【讨论】:

      猜你喜欢
      • 2014-10-04
      • 2018-03-31
      • 2018-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多