WebAPI POST请求参数为null

时间:2017-12-26 13:08:04

标签: c# asp.net asp.net-web-api

我正在尝试对json对象执行POST请求并将其转换为类,但它无效。这是发送对象的JS:

var TheAjaxData = {
    'Property1': 'TheValue1',
    'Property2': 'TheValue2',
    'Property3': 'TheValue3'
}

$.ajax({
    url: "/thewebapi/themethod",
    type: "POST",
    data: TheAjaxData,
    contentType: 'application/json; charset=utf-8',
    success: function (msg, textStatus, request) {
        console.log(msg);
    }
});

WebAPI收到请求,因此我知道路由正确,但TheObject为空。这是代码:

[RoutePrefix("thewebapi")]
public class TheWebAPIController : ApiController
{
    [Route("themethod")]
    public HttpResponseMessage Post([FromBody] TheRequestObjectModel TheObject)
    {
        var testvalue = TheObject.Property1;
    }

    public class TheRequestObjectModel
    {
        public string Property1 { get; set; }
        public string Property2 { get; set; }
        public string Property3 { get; set; }
    }
}

这需要使用POST,而不是GET。我很确定我很接近,但它不起作用。我需要更改什么才能将我发送的对象转换为TheRequestObjectModel

2 个答案:

答案 0 :(得分:2)

尝试将js对象转换为json(因为json格式化对象中的数据):

var TheAjaxData = {
    'Property1': 'TheValue1',
    'Property2': 'TheValue2',
    'Property3': 'TheValue3'
}

$.ajax({
    url: "/thewebapi/themethod",
    type: "POST",
    data: JSON.stringify(TheAjaxData),
    contentType: 'application/json; charset=utf-8',
    success: function (msg, textStatus, request) {
        console.log(msg);
    }
});

答案 1 :(得分:1)

如果要使用[FromBody]修饰API操作,则应在从客户端发布数据时序列化为Json。您可以使用JSON.stringify(TheAjaxData)

$.ajax({
    url: "/thewebapi/themethod",
    type: "POST",
    data: JSON.stringify(TheAjaxData),
    contentType: 'application/json; charset=utf-8',
    success: function (msg, textStatus, request) {
        console.log(msg);
    }
});

另一个选择是删除[FromBody]属性并直接传递javascript对象。实际上,在您的情况下TheRequestObjectModel只有字符串属性,并且它不包含另一个复杂对象。因此,最好删除[FromBody]属性。

[Route("themethod")]
public HttpResponseMessage Post(TheRequestObjectModel TheObject)
{
    var testvalue = TheObject.Property1;
}

$.ajax({
    url: "/thewebapi/themethod",
    type: "POST",
    data: TheAjaxData,
    contentType: 'application/json; charset=utf-8',
    success: function (msg, textStatus, request) {
        console.log(msg);
    }
});