【问题标题】:Remove attribute from controller which was set in config从配置中设置的控制器中删除属性
【发布时间】:2018-08-18 22:59:34
【问题描述】:

当我的Web API 项目如下请求http 时,我已编写自定义属性以将请求重定向到https,如下所示

public class RedirectToHttpAttribute: AuthorizeAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
            {
                var response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Found, "");
                var uri = new UriBuilder(actionContext.Request.RequestUri);
                uri.Scheme = Uri.UriSchemeHttps;
                uri.Port = 44326;
                response.Headers.Location = uri.Uri;
                actionContext.Response = response;
            }
        }
    }

现在我想为我的所有控制器和动作设置这个属性,所以我在WebApiConfig 中添加了这个。

config.Filters.Add(new RedirectToHttpAttribute());

现在有一个控制器需要同时允许httphttps。为了使这成为可能,我必须从WebApiConfig 中删除上面的行,并添加到除问题中的一个之外的所有控制器。我可以很容易地做到这一点,因为我的控制器很少,但是如果我有很多控制器,那么解决方案是什么,因为它很可能会产生错误来装饰每个控制器?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-web-api


    【解决方案1】:

    您可以通过创建第二个属性并修改现有的重定向过滤器来做到这一点。

    类似这样的:

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class AllowHttpAttribute : Attribute
    {
    }
    
    public class RedirectToHttpsAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext.ActionDescriptor.GetCustomAttributes<AllowHttpAttribute>(false).Any())
            {
                return;
            }
    
            // Perform the redirect to HTTPS.
        }
    }
    

    然后在你的控制器(或动作)上:

    [AllowHttp]
    public class ValuesController : ApiController
    {
        // ...
    }
    

    【讨论】:

      猜你喜欢
      • 2013-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多