2016-10-10 96 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 
); 
這條路線