c# - 从控制器中删除配置中设置的属性
问题描述
我已经编写了自定义属性以将请求重定向到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());
现在有一个控制器,我需要同时允许http
和https
。WebApiConfig
为了使这成为可能,我必须从除问题中的一个控制器之外的所有控制器中删除并添加上面的行。我可以很容易地做到这一点,因为我的控制器很少,但是如果我有很多控制器,那么解决方案是什么,因为它很可能会产生错误来装饰每个控制器?
解决方案
您可以通过创建第二个属性并修改现有的重定向过滤器来做到这一点。
像这样的东西:
[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
{
// ...
}
推荐阅读
- reactjs - 为什么在使用 axios 的 ReactJS 中会发生此错误
- angular - Angular 6 和引导程序
- c# - WPF,树视图是鼠标悬停仅在第一次后有效
- android - Instagram API 平台移动 oAuth 错误
- c# - 在 URI 中遇到尾随 & 时如何处理奇怪的行为?
- python - 循环一个 csv,试图写入另一个 csv
- rest - 使用依赖项部署 REST API
- android - 如何制作微调器提示多行?
- winforms - 从工具箱拖放到 Windows 窗体设计器时的对象引用异常
- php - 使用 Laravel 路由在 Blade 模板引擎中构建带有参数的命名路由