2012-12-17 16 views
11

का उपयोग कर मैं यहां अपने कोड में एक अपवाद फेंक WebAPI के साथ एक समस्या मिल गया है सौंपा नहीं किया गया है:भीतरी हैंडलर WebAPI Delegating हैंडलर

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

यह मार्ग डिफ़ॉल्ट एपीआई मार्ग है। किसी भी मदद की बहुत सराहना की ....

उत्तर

29

उत्तर here और उदाहरण हैंडलर here मिला।

आपको इनरहैंडलर को सेट करने की आवश्यकता है जिसे आप अनुरोध भेजना चाहते हैं।

बस अपने निर्माता से जोड़ें:

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

कभी-कभी आप RESTful यूआरएल तुम सच में अगर यह अनुरोध कर जांच होनी चाहिए आपके नियंत्रक में मौजूद है। मैंने कभी इस तरह के अपवाद का सामना किया है जो गलत यूआरएल मैच के कारण हुआ था। धन्यवाद।

संबंधित मुद्दे