jaf*_*ffa 12 asp.net asp.net-web-api asp.net-web-api-routing
我在我的代码中遇到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;
});
}
Run Code Online (Sandbox Code Playgroud)
例外情况发生在线上:
base.SendAsync(request, cancellationToken);
Run Code Online (Sandbox Code Playgroud)
我不知道如何解决这个问题.我的路由表中有以下内容:
routes.MapHttpRoute("NoAuthRequiredApi", "api/auth/", new { Controller = "Auth" });
routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional }, null, new WebApiAuthenticationHandler());
Run Code Online (Sandbox Code Playgroud)
发生这种情况的路线是DefaultApi路线.任何帮助非常感谢....
Mar*_*nes 30
您需要设置希望传递请求的InnerHandler.
只需将其添加到构造函数中:
public class WebApiAuthenticationHandler : DelegatingHandler
{
public WebApiAuthenticationHandler(HttpConfiguration httpConfiguration)
{
InnerHandler = new HttpControllerDispatcher(httpConfiguration);
}
Run Code Online (Sandbox Code Playgroud)
并在创建新实例时传递对GlobalConfiguration的引用:
routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional }, null, WebApiAuthenticationHandler(GlobalConfiguration.Configuration));
Run Code Online (Sandbox Code Playgroud)
正如丹尼尔·罗斯(Daniel Roth)在当前投票最高的答案的链接中提到的,您的处理程序链不得以.DelegatingHandler
\n\nDelegatingHandler \xe2\x80\x9cdelegates\xe2\x80\x9d 对使用 InnerHandler 属性提供的内部处理程序的发送调用。DelegatingHandler 用于将俄罗斯娃娃模型中的消息处理程序链接在一起。错误消息表明未提供 InnerHandler。通常在客户端上,您希望最内部的处理程序是 HttpClientHandler ,它将发送请求并处理响应。
\n
解决该错误的最简单方法是使用构造函数重载进行设置,InnerHandler如下所示:
public class CustomHandler : DelegatingHandler\n{\n public CustomHandler()\n : base(new HttpClientHandler())\n {\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n没有必要传入 anHttpConfiguration并将其包装在 an 中HttpControllerDispatcher。
| 归档时间: |
|
| 查看次数: |
11431 次 |
| 最近记录: |