2016-10-10 99 views
0

我希望能够根据用户定义的布尔值打开/关闭所有我的web api路由。目前这可以来自Web.config。如果此标志设置为false,我希望能够响应任何请求(任何和所有路线天气有效或没有),并显示一条错误消息 - “.. api已禁用...”Web API动态启用/禁用响应

Just toying with这里的想法是用一些伪代码覆盖控制器的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()拦截所有请求(S)?

回答

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 
); 
这条路线