Web API 2 对于 Content-Length 要求严格

最近在做一个工具,里面有一个发起http请求的操作,虽然工具不是用.NET写的,但是测试用服务器软件是.NET写的。在这里选择了ASP.NET MVC和Web API 2。
首先预定义Student与Human类,ASP.NET MVC定义了一个限定HttpPost的方法,要求传递一个Student对象。ASP.NET Web API 2 定义了一个限定HttpPost的方法,要求也是传递一个Student对象。

public class Human
{
    public string Name { get; set; }
    public Int32 Age { get; set; }
}

public class Student : Human
{
    public String[] School { get; set; }
}

[System.Web.Mvc.HttpPost]
public dynamic Req(Student student)
{
    if (student != null)
    {
        return student;
    }
    return new Student { Name = "Joe", Age = 23, School = new string[] { "Oracle" } };
}

[HttpPost]
public Student Req(Student student)
{
    if (student != null)
    {
        return student;
    }
    return new Student { Name = "Joe", Age = 23, School = new string[] { "Oracle" } };
}

在工具里向这两个地址发起Post请求,头部设置Content-Type为application/json,正文为Student对象的JSON序列化。

然后在跟踪的时候发现,Web API 2的Student对象一直为Null,也就是Web API 2没有拿到请求正文的对象。然而MVC是拿到了的。这个时候陷入了江局,MVC能拿到代表正文内容是发出去了的,序列化内容也是没有问题的,但是Web API 2拿不到就说明请求还存在问题。

在StackOverflow和一些乱七八糟的网站上看了半天,似乎总是在围绕[FromBody],事实上不论加不加我这都是Null。一直检索似乎也不是个事,索性直接对比ASP.NET MVC与ASP.NET Web API 2的请求信息,结果发现一个问题:

发送给Web API 2的请求的Content-Length是0,但是MVC的则是实际长度。联想到在请求发起时的确没有设定Content-Length,估计是MVC自动标准化了请求的信息,而Web API 2严格遵循http标准,当Content-Length为0时便不再处理正文内容。

所以如果需要写代码对Web API 2发起请求,请不要忘记设置Content-Length,否则会忽略掉正文内容。

posted @ 2017-08-21 13:30  Johnwii  阅读(703)  评论(0编辑  收藏  举报