Asp.net Core 2 API POST对象是否为NULL?

编程入门 行业动态 更新时间:2024-10-21 18:58:51
本文介绍了Asp Core 2 API POST对象是否为NULL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个带有某些测试功能的 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?

本文发布于:2023-11-05 07:58:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1560299.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   Core   net   Asp   NULL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!