gpt4 book ai didi

asp.net - 尚未使用 Web Api Delegatinghandler 分配内部处理程序

转载 作者:行者123 更新时间:2023-12-03 23:04:01 25 4
gpt4 key购买 nike

我遇到了 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 路由。非常感谢任何帮助......

最佳答案

找到答案 here和一个示例处理程序 here .

您需要设置您希望将请求传递到的 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));

关于asp.net - 尚未使用 Web Api Delegatinghandler 分配内部处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13922618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com