在asp.net Web API中使用FromBody时,字符串值是Empty [英] string value is Empty when using FromBody in asp.net web api

查看:53
本文介绍了在asp.net Web API中使用FromBody时,字符串值是Empty的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用asp.net核心Web API.以下是我的简单post函数,它具有单个字符串参数.问题是当我使用[FromBody]时,字符串保持为空.我正在使用PostMan来测试我的服务.我希望原始数据从客户端传递到我的控制器.在邮递员中,我选择的是RAW类型,我设置标题Content-Type文本/纯文本.Raw Body包含"Hello World"字符串.

I am using asp.net core web api. below is my simple post function which is having a single string parameter. The problem is when I use [FromBody] the string stays null. I am using PostMan to test my service. I want raw data to pass from client to my controller. In Postman I am selecting body type RAW and I set the header Content-Type text/plain. The Raw Body contains Just "Hello World" string.

[HttpPost]
        [Route("hosted-services/tokenize-card")]
        public IActionResult Test([FromRoute]decimal businessKey,[FromBody] string body)
        {
            var data = businessKey;
            return new JsonResult("Hello World");
        }

推荐答案

类似于

当参数具有[FromBody]时,Web API使用Content-Type标头选择格式器.

When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter.

默认情况下仅支持XML和JSON内容类型.因此,您需要使用 application/xml application/json 或注册自定义的 IInputFormatter .

Only XML and JSON content-types are supported by default. So you need to use application/xml, application/json or register a custom IInputFormatter.

接下来,您需要发送与所选内容类型匹配的内容.对于json,如果参数为 int ,请发送一个数字.如果是一个类,则发送一个json对象.如果是字符串,请发送json字符串.等等.

Next, you need to send a content that match the selected content-type. For json, if the parameter is int send a number. If it's a class, send a json object. If it's a string, send a json string. Etc.

int => 14
string => "azerty"
class => { "propName" : "value" }
Array => []
... => ...

在您的情况下,您应该发送 application/json 内容类型和内容:

In your case you should send application/json content-type and as content :

"Hello string"

不只是

Hello string

Aspnet核心json输入格式化程序实现

Aspnet核心xml输入格式化程序实现

示例:创建CSV媒体格式化程序

这篇关于在asp.net Web API中使用FromBody时,字符串值是Empty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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