Search code examples
asp.netasp.net-web-apiasp.net-web-api-routing

The inner handler has not been assigned using WebApi Delegating handler


I have got a problem with WebApi throwing an exception here in my code:

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

The exception is happening on the line:

base.SendAsync(request, cancellationToken);

I haven't a clue how to fix this. I have the following in my route table:

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

The route this happens on is the DefaultApi route. Any help greatly appreciated....


Solution

  • Found the answer here and an example handler here.

    You need to set the InnerHandler you want the request passed on to.

    Simply add this to your constructor:

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

    And pass in a reference to GlobalConfiguration when creating a new instance:

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