使用 jQuery 将 JSON 对象发送到 MVC 6 WebApi 控制器

Send JSON object to MVC 6 WebApi controller using jQuery

我无法将 JSON 对象发送到我的 MVC 6 WebApi 控制器。

当我在 fiddler 中查看 RAW 数据时,我当前发送的是:

Username=brugernavn&Password=adgangskode&DocumentId=document.dotx

我认为我的控制器期望收到的是:

{"Username":"brugernavn","Password":"adgangskode","DocumentId":"document.dotx"}

我的控制器代码:

namespace DemoApp.Controllers
{
    [Route("api/[controller]")]
    public class DocumentController : Controller
    {

        // POST: api/documentcontroller/GetDocumentInformation
        [HttpPost]
        [Route("[action]")]
        public string GetDocumentInformation([FromBody] GetDocumentInformationRequest documentInformationRequest)
        if (documentInformationRequest == null)
        {
            return "null";
        } else {
            return "ok";
        }
    }
}

我的 GetDocumentInformationRequest 模型 class:

public class GetDocumentInformationRequest
{
    public string Username { get; set; }
    public string Password { get; set; }
    public string DocumentId { get; set; }
}

我的jQuery代码:

var source = {
    'Username': 'brugernavn',
    'Password': 'adgangskode',
    'DocumentId': documentID
}
var apiUrl = location.origin + "/api/documentcontroller/GetDocumentInformation";
$.ajax({
    type: "POST",
    dataType: "json",
    url: apiUrl,
    data: source,
    success: function (data) {
        alert(data);
    },
    error: function (error) {
        var x = error; //break here for debugging.
    }
});

ajax 请求确实命中了控制器,但 documentInformationRequest 参数为空。

此外,ajax 请求每次都在错误块中结束,但那是因为控制器当前只有 returns "null",这是无效的 JSON ... (它执行 return 代码 200,并且没有抛出任何错误。)

我已经尝试了 ajax 请求的多种变体,但到目前为止 none 已经正确地将 JSON 对象发送到控制器。

你只需要使用JSON.stringify

$.ajax({
   type: "POST",
   dataType: "json",
   url: apiUrl,
   data: JSON.stringify(source),
   success: function (data) {
       alert(data);
   },
   error: function (error) {
       var x = error; //break here for debugging.
   }
});

感谢维塔利的回答。 与此同时,我确实偶然发现了一个类似的解决方案,尽管我还需要在控制器接受数据之前添加 contentType 参数。

所以就我而言,完整的答案如下:

$.ajax({
    type: "POST",
    dataType: "json",
    url: apiUrl,
    data: JSON.stringify(source),
    contentType: "application/json",
    success: function (data) {
        alert(data);
    },
    error: function (error) {
        var x = error; //break here for debugging.
    }
});