Asp.net

尚未使用 WebApi Delegating 處理程序分配內部處理程序

  • July 19, 2018

我遇到了 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 路由。任何幫助都非常感謝….

在此處找到答案並此處找到範例處理程序。

您需要設置要將請求傳遞給的 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));

引用自:https://stackoverflow.com/questions/13922618