【问题标题】:Web API Dynamic Enable/Disable ResponseWeb API 动态启用/禁用响应
【发布时间】:2016-10-11 03:38:06
【问题描述】:

我希望能够根据用户定义的布尔值打开/关闭我的所有 Web api 路由。目前这可以来自 Web.config。如果此标志设置为 false,我希望能够使用错误消息响应任何请求(任何和所有路由天气是否有效)——“..api is disabled...”

这里只是玩弄用一些伪代码覆盖控制器的 Initialize 方法的想法。我想这会假设被请求的路由在我想要响应任何请求的地方是有效的。我什至不确定是否可以将 IsEnabled 属性注入到 Configuration.Properties 集合中。寻找任何关于如何关闭路由并根据设置做出相应响应的建议。

谢谢

 public class MyController : ApiController
    {
        protected override void Initialize(HttpControllerContext controllerContext)
        {
            if (!Convert.ToBoolean(controllerContext.Configuration.Properties["IsEnabled"]))
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Api is currently disabled."));
            }
            base.Initialize(controllerContext);
        }

编辑:可能使用 HttpConfiguration.MessageHandlers.Add() 来拦截所有请求?

【问题讨论】:

    标签: asp.net-mvc asp.net-web-api asp.net-web-api2


    【解决方案1】:

    尝试自定义DelegatingHandler

    internal class BaseApiHandler : DelegatingHandler
    {
        protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Forbidden);
    
            var allowRequest = //web config value
    
            // if request is allowed then let it through to the next level
            if(allowRequest)
                response = await base.SendAsync(request, cancellationToken);
    
            // set response message or reasonphrase here
    
            // return default result - forbidden
            return response;
       }
    }
    

    编辑您的 webapiconfig.cs 以在顶部包含此路由

    config.Routes.MapHttpRoute(
        name: "Default",
        routeTemplate: "{*path}",
        handler: HttpClientFactory.CreatePipeline
        (
            innerHandler: new HttpClientHandler(),
            handlers: new DelegatingHandler[] { new BaseApiHandler() }
        ),
        defaults: new { path = RouteParameter.Optional },
        constraints: null
    );
    

    【讨论】:

      猜你喜欢
      • 2015-10-07
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 2022-01-19
      • 2021-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多