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

标签 c# rest asp.net-web-api asp.net-web-api2 owin

我正在开发一个 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/

相关文章:

c - 使用 Ulfius 实现 REST API - URI 定义

c# - 我们可以将数据集传递给 Web 服务方法吗?如果是,那么如何?

python - Django - 使用从类似 REST 的 API 检索的数据构建报告的应用程序

安卓注释 : @Rest annotation compile error

c# - Web API 2/MVC 5 : Attribute Routing passing parameters as querystring to target different actions on same controller

azure - 将 Azure AppServices 中的 Web API 的访问限制为 Azure Function 应用程序,同时允许其他服务访问其他 Web api 和网页

vb.net - CRM16 - 从 WebApi 触发自定义操作

c# - 如何在 ASP.NET Core 中默认防止 CSRF

c# - 如何在 C# Windows 窗体中使用 linq 在组合框中显示多个字段?

c# - std::vector<bool> a (b, false);在 C# 中