从 ASP.NET Web API 中的 POST 读取 JSON 对象

Read JSON object from POST in ASP.NET Web API

我正在尝试将 POST 数据绑定到对象,如下所示:

[Route("ta_iba/test")]
[HttpPost]
public string test(Photo p)
{
     ............
}

public class Photo
{
    public string url { get; set; }
    public string caption { get; set; }
    public int width { get; set; }
    public int height { get; set; }
}
WebApiConfig:     
        config.Formatters.Add(new JsonMediaTypeFormatter());

我正在使用 fiddler 进行测试:

Header:
User-Agent: Fiddler
ContentType: application/json
Host: localhost:50653
Content-Length: 50
Body:
{"url":"xxxx","caption":"yyy","width":50,"height":50}

但我收到错误 HTTP/1.1 415 Unsupported Media Type。有什么想法吗?

您需要将请求参数发送为Content-Type,而不是ContentType:

Header:
User-Agent: Fiddler
Content-Type: application/json
Host: localhost:50653
Content-Length: 50
Body:
{"url":"xxxx","caption":"yyy","width":50,"height":50}