繁体   English   中英

WebAPI POST请求参数为空

[英]WebAPI POST request parameters are null

我正在尝试执行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为null。 这是代码:

[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

尝试将您的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);
    }
});

如果要使用[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);
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM