gpt4 book ai didi

c# - 在 WebApi2 + Owin 中使用 AuthorizeAttribute 时,HEAD 请求因 System.Net.ProtocolViolationException 而失败

转载 作者:太空宇宙 更新时间:2023-11-03 15:02:40 25 4
gpt4 key购买 nike

我正在开发一个 Restful API,我需要在发出实际的 DELETE 请求之前检查授权。所以我认为使用 HEAD 方法作为预检检查会很好。

我预计使用 HEAD 方法的未经授权的请求将返回没有正文的 401/403 响应。然而,事实证明 WebApi2 崩溃并出现以下异常并关闭连接:

Exception caught: 'System.Net.ProtocolViolationException' in System.dll ("Bytes to be written to the stream exceed the Content-Length bytes size specified.")

其他 HTTP 方法(DELETE、GET)似乎工作正常 - 返回 401 响应。

我可以通过 GET 请求来解决它,但这似乎是 WebApi 中的一个错误。 AuthorizeAttribute总是添加一个内容,不管原来的请求方法是什么。

我的问题是:这是错误还是预期的行为,我为什么不应该在这里使用 HEAD 方法?

这是一个重现该问题的示例程序:

namespace OwinServer
{
[Authorize]
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new[] { "value1", "value2" };
}

//HEAD api/values
public void Head()
{

}

//DELETE api/values
public void Delete()
{

}
}

class Program
{
static void Main(string[] args)
{
var baseAddress = "http://localhost:9000/";

// Start OWIN host
using (WebApp.Start(baseAddress, Configuration))
{
Console.WriteLine("Host started");
Console.ReadLine();
}
}

public static void Configuration(IAppBuilder appBuilder)
{
// Configure Web API for self-host.
var config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

appBuilder.UseWebApi(config);
}
}
}

可以使用 PowerShell 测试该行为:

失败的示例请求:

Invoke-WebRequest -Uri 'http://localhost:9000/api/values' -Method HEAD

有效的示例请求:

Invoke-WebRequest -Uri 'http://localhost:9000/api/values' -Method DELETE

最佳答案

这个已经讨论过了https://github.com/aspnet/AspNetWebStack/issues/189 .似乎他们希望您最终处理它。

关于c# - 在 WebApi2 + Owin 中使用 AuthorizeAttribute 时,HEAD 请求因 System.Net.ProtocolViolationException 而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45377956/

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