首页 > 解决方案 > 从控制器中删除配置中设置的属性

问题描述

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

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());

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

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

解决方案


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

像这样的东西:

[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
{
    // ...
}

推荐阅读