问题
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....
回答1:
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));
回答2:
Sometimes you should check the RESTful Url you request if it really does exist in your controller. I have ever encountered this kind of exception which was caused by the wrong URL match. thanks.
来源:https://stackoverflow.com/questions/13922618/the-inner-handler-has-not-been-assigned-using-webapi-delegating-handler