我遇到了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路线。任何帮助都非常感谢....
答案 0 :(得分:29)
您需要设置希望传递请求的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));
答案 1 :(得分:2)
有时您应该检查您请求的RESTful Url,如果它确实存在于您的控制器中。我遇到过这种由错误的URL匹配引起的异常。感谢。