2016-10-10 17 views
0

ユーザーが定義したブール値に基づいて、すべてのWeb APIルートをオン/オフできるようにします。今のところこれはWeb.configから来ることができます。このフラグがfalseに設定されている場合、エラーメッセージ "--api is disabled ..."が表示され、すべてのリクエスト(すべてのルートと天候が有効であるかどうか)に応答できるようにしたいとします。Web API動的有効/無効応答

コントローラーのInitializeメソッドをいくつかの擬似コードでオーバーライドする方法です。私はこれは、要求されているルートが有効であるにもかかわらず、これまでどんな要求に対しても応答したいと考えていると思います。 IsEnabledプロパティをConfiguration.Propertiesコレクションに挿入できるかどうかはわかりません。どのような推奨事項を探して、ルーティングをシャットダウンし、それに応じて設定に基づいて対応することができます。すべての要求(複数可)を傍受することが可能に使用HttpConfiguration.MessageHandlers.Add():

おかげ

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

EDIT?

答えて

1

トップ

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 
); 
でこのルートを含めるようにカスタム 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をお試しください

関連する問題