Netcore,JSON参数始终为null

时间:2017-07-17 22:59:49

标签: javascript c# json model-view-controller asp.net-core

我不知道我做错了什么或改变了什么。 我正在尝试将JSON参数发送到netcore 1.1中的mvc控制器

MVC控制器:

[HttpPost]
public JsonResult Test1(DepartmentDTO departmentDto, int testId)
{
    return Json(departmentDto);
}
public partial class DepartmentDTO
{
    public int DepartmentID { get; set; }
    public string Description{ get; set; }
}

Javascript POST:

var req = {
    method: 'POST',
    url: "/Department/Test1",
    headers: {
        'Content-Type': 'application/json;charset=utf-8'
    },
    data: JSON.stringify({
        "departmentDto": { "DepartmentID": 1, "Description": "TEST" },
        "testId": 1
    }),
};
var promise = $http(req).then(function successCallback(response) {
    if (response.data.departmentID == 0) {
        alert("Wrong")
    }
    return response.data
}, function errorCallback(response) {
    return { success: false, message: response.data };
});

所有参数始终为null:departmentDto& testId 谢谢你的帮助。

1 个答案:

答案 0 :(得分:2)

[FromBody]只能使用一次。 Body流只是前进。

建议:

[Route("Department")]
public class DepartmentController : Controller {
    [HttpPost("Test1/{testId:int}")] //Matches POST Department/Test1/1
    public IActionResult Test1(int testId, [FromBody]DepartmentDTO departmentDto) {
        return Json(departmentDto);
    }
}

并修改请求

var req = {
    method: 'POST',
    url: "/Department/Test1/1",
    headers: {
        'Content-Type': 'application/json;charset=utf-8'
    },
    data: JSON.stringify({ "DepartmentID": 1, "Description": "TEST" }),
}; 

或者创建一个与客户端字符串化相匹配的新对象模型,并将其作为标记为[FromBody]的单个操作参数