【发布时间】:2015-08-25 08:31:26
【问题描述】:
我无法将 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 模型类:
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 请求每次都会在错误块中结束,但那是因为控制器当前只返回“null”,这不是有效的 JSON... (它确实返回了一个代码 200,并且没有抛出任何错误。)
我尝试了许多 ajax 请求的变体,但到目前为止,没有一个可以正确地将 JSON 对象发送到控制器。
【问题讨论】:
标签: jquery json asp.net-web-api asp.net-core-mvc