我有一个带有某些测试功能的 Core 2 API设置. (Visual Studio 2017)
I have a Core 2 API setup with some test function. (Visual Studio 2017)
使用邮递员,我将原始数据发布到该方法中,但是模型只是空白吗?为什么?
Using postman I do a post with the raw data to that method, but the model is just blank? Why?
// POST api/Product/test [HttpPost] [Route("test")] public object test(MyTestModel model) { try { var a = model.SomeTestParam; return Ok("Yey"); } catch (Exception ex) { return BadRequest(new { message = ex.Message }); } } public class MyTestModel { public int SomeTestParam { get; set; } }
推荐答案
您需要在模型中包含[FromBody]属性:
You need to include the [FromBody] attribute on the model:
[FromBody] MyTestModel model有关更多信息,请参见安德鲁·洛克(Andrew Lock)的帖子 :
See Andrew Lock's post for more information:
为了在ASP.NET Core中正确绑定JSON,必须修改操作以在参数上包含属性[FromBody].这告诉框架使用请求的内容类型标头来决定使用哪个已配置的IInputFormatter进行模型绑定.
In order to bind the JSON correctly in ASP.NET Core, you must modify your action to include the attribute [FromBody] on the parameter. This tells the framework to use the content-type header of the request to decide which of the configured IInputFormatters to use for model binding.
正如@anserk在评论中指出的,这还要求将Content-Type标头设置为application/json.
As noted by @anserk in the comments, this also requires the Content-Type header to be set to application/json.
更多推荐
Asp.net Core 2 API POST对象是否为NULL?
发布评论