gpt4 book ai didi

.net - 在 DelegatingHandler 中设置 WWW-Authenticate 响应头会导致对 w2k3 的破坏

转载 作者:行者123 更新时间:2023-12-04 15:35:00 25 4
gpt4 key购买 nike

我通过发送 session token 来使用自定义身份验证机制。在 DelegatingHandler 中检查 token 的存在,该处理程序相应地设置当前主体。如果主体未被授权调用 ApiController 方法,则 Controller 发送 401 Unauthorized 状态。由于 RFC 2616 要求在发送 401 响应时始终设置 WWW-Authenticate header ,因此我的 DelegatingHandler 会处理此问题。

现在,在 Web API 自托管的情况下,应该以 401 响应的请求在 Windows 7 上正常工作,但在 Windows Server 2003 上,它以“远程主机强制关闭现有连接”为异常(exception)。此外,我注意到 Controller 方法中的断点在 W2k3 上被击中两次,而在 Win7 中一次,就好像 HttpClient 在收到 401 响应时以某种方式重试了请求。

当我取消注释带有 WWW-Authenticate header 的行时,程序可以正常工作。请参阅下面的代码示例,了解控制台应用程序中的简约再现示例。

TestController.cs:

public class TestController : ApiController
{
public HttpResponseMessage Get()
{
return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "go away");
}
}

AuthenticationHandler.cs:
public class AuthenticationHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>(task =>
{
HttpResponseMessage response = task.Result;
if ( response.StatusCode == HttpStatusCode.Unauthorized &&
!response.Headers.Contains("WWW-Authenticate") )
{
// comment out this line and the code works
response.Headers.Add("WWW-Authenticate", "SessionToken");
}
return response;
});
}
}

程序.cs:
    static void Main(string[] args)
{
HttpSelfHostConfiguration config = new HttpSelfHostConfiguration("http://localhost:81");
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}"
);
config.MessageHandlers.Add(new AuthenticationHandler());

using ( HttpSelfHostServer server = new HttpSelfHostServer(config) )
using ( HttpClient client = new HttpClient() )
{
server.OpenAsync().Wait();

try
{
HttpResponseMessage response = client.GetAsync("http://localhost:81/api/test").Result;
Console.Out.WriteLine(response.StatusCode);
}
catch ( AggregateException ex )
{
Console.Out.WriteLine(ex.ToString());
}

server.CloseAsync().Wait();
}

Console.In.ReadLine();
}

我是否正确调用了 API?任何想法可能是错误的?

最佳答案

您需要安装 .net Framework 4.0.3。 .net 框架的先前版本无法设置 www-authenticate header 。获取 here ,有关该问题的更多信息在 KB2600211 .

关于.net - 在 DelegatingHandler 中设置 WWW-Authenticate 响应头会导致对 w2k3 的破坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16981832/

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