模型没有从POST请求中获取值

时间:2013-06-29 00:33:03

标签: asp.net-mvc asp.net-mvc-4 asp.net-web-api

我正在尝试将一些东西发布到我的Web API,但不管我做什么,模型值总是设置为null。

我尝试过以下请求(从fiddler复制的跟踪):

POST http://localhost:53176/api/Profile HTTP/1.1
Host: localhost:53176
Connection: keep-alive
Content-Length: 40
Accept: application/xml, text/xml, */*; q=0.01
Origin: http://localhost:53176
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Referer: http://localhost:53176/SignUp
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Cookie: ASP.NET_SessionId=do5ddqwghl3v0bhlgr3pyicb

{"InputEmail":"aa","UserName":"asd"}

更新 以及以下内容:

POST http://localhost:53176/api/Profile HTTP/1.1
Host: localhost:53176
Connection: keep-alive
Content-Length: 44
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://localhost:53176
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36
Content-Type: application/json
Referer: http://localhost:53176/SignUp
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Cookie: ASP.NET_SessionId=do5ddqwghl3v0bhlgr3pyicb

{"InputEmail":"asdas","UserName":"dasd"}

我的api看起来像:

    //here I have also tried [FromBody]
    public MyDto Post(MyDto input)
    {
       return input;
    }

MyDto有两个属性,是:

public class MyDto 
{
    string InputEmail { get; set; }
    string UserName { get; set; }
}

有人能够告诉我这段代码中的问题是什么,或者我有什么遗漏?

我还想知道如何(或在哪里)将调试器放在webapi代码中的某个位置,以便在webapi尝试反序列化之前查看实际请求是什么。

1 个答案:

答案 0 :(得分:1)

您的Content-Type标题为application/x-www-form-urlencoded,但您的正文包含json数据。将您的内容类型标头修改为application/jsontext/json

修改: 设置您的媒体资源Public