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

时间:2017-07-28 16:05:51

标签: 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

1 个答案:

答案 0 :(得分:0)

对此已进行了https://github.com/aspnet/AspNetWebStack/issues/189的讨论。似乎他们希望您在最后解决它。