Asp.net Core 2 API POST对象是否为NULL? [英] Asp.net Core 2 API POST Objects are NULL?

查看:51
本文介绍了Asp.net Core 2 API POST对象是否为NULL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有某些测试功能的.net Core 2 API设置. (Visual Studio 2017)

I have a .net 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆