2012-12-17 65 views
11

我有跟的WebAPI在我的代碼在這裏拋出異常的問題分配:內部處理程序尚未使用的WebAPI委派處理

public class WebApiAuthenticationHandler : DelegatingHandler 
    { 
     private const string AuthToken = "AUTH-TOKEN"; 

     protected override Task<HttpResponseMessage> SendAsync(
      HttpRequestMessage request, CancellationToken cancellationToken) 
     {     
      var requestAuthTokenList = GetRequestAuthTokens(request); 
      if (ValidAuthorization(requestAuthTokenList)) 
      { 
       // EXCEPTION is occuring here!.... 
       return base.SendAsync(request, cancellationToken); 
      } 

      /* 
      ** This will make the whole API protected by the API token. 
      ** To only protect parts of the API then mark controllers/methods 
      ** with the Authorize attribute and always return this: 
      ** 
      ** return base.SendAsync(request, cancellationToken); 
      */ 
      return Task<HttpResponseMessage>.Factory.StartNew(
       () => 
       { 
        var resp = new HttpResponseMessage(HttpStatusCode.Unauthorized) 
        { 
         Content = new StringContent("Authorization failed") 
        }; 

        //var resp = new HttpResponseMessage(HttpStatusCode.Unauthorized);                     
        //resp.Headers.Add(SuppressFormsAuthenticationRedirectModule.SuppressFormsHeaderName,"true"); 
        return resp; 
       }); 
     } 

唯一的例外是上線發生的事情:

base.SendAsync(request, cancellationToken); 

我不知道如何解決這個問題。我在我的路由表如下:

routes.MapHttpRoute("NoAuthRequiredApi", "api/auth/", new { Controller = "Auth" }); 
    routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional }, null, new WebApiAuthenticationHandler()); 

這發生在這條路線是DefaultApi路線。任何幫助非常感謝....

回答

29

找到答案here和示例處理程序here

您需要設置您希望將請求傳遞給的InnerHandler。創建一個新的實例時

public class WebApiAuthenticationHandler : DelegatingHandler 
{ 
    public WebApiAuthenticationHandler(HttpConfiguration httpConfiguration) 
    { 
     InnerHandler = new HttpControllerDispatcher(httpConfiguration); 
    } 

並傳遞到GlobalConfiguration參考:

這隻需添加到您的構造

routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional }, null, WebApiAuthenticationHandler(GlobalConfiguration.Configuration)); 
2

有時你應該檢查是否你要求真REST風格的網址確實存在於你的控制器中。我遇到過這種由於URL匹配錯誤而導致的異常。謝謝。

相關問題