Null value when Pass values [FromBody] to post method by Postman plugin(Postman插件将值[FromBody]传递给post方法时的空值)
问题描述
我在 ASP.net Web API 中使用 api 控制器,我需要通过 [FromBody] 类型将值传递给 post 方法..
I use api controller in ASP.net web API and i need to pass value to post method by [FromBody] type..
[HttpPost]
public HttpResponseMessage Post( [FromBody]string name)
{
....
}
我使用 Postman 插件,但是当发送到 name 的 post 方法值始终为 null.. 遵循此图像:
i use Postman plugin but when send to post method value of name always is null.. follow this image:
在 Post 方法中:
and in Post methods :
为什么会这样?!
推荐答案
你不能使用 json 和 FromBody 绑定单个原始字符串,json 将传输一个对象,控制器将依次期望一个复杂对象(模型).如果您只想发送单个字符串,请使用 url 编码.
You can't bind a single primitive string using json and FromBody, json will transmit an object and the controller will expect an complex object (model) in turn. If you want to only send a single string then use url encoding.
在您的标题集上
Content-Type: application/x-www-form-urlencoded
POST 请求消息正文的正文应为 =saeed(基于您的测试值),仅此而已.对于未知/变量字符串,您必须对值进行 URL 编码,这样您就不会意外地因输入字符而转义.
The body of the POST request message body should be =saeed (based on your test value) and nothing else. For unknown/variable strings you have to URL encode the value so that way you do not accidentally escape with an input character.
创建一个模型并使用它.
Create a model and use that instead.
消息正文值:{"name":"saeee"}
c#
public class CustomModel {
public string Name {get;set;}
}
控制器方法
public HttpResponseMessage Post([FromBody]CustomModel model)
备用 2
使用 URI 而不是消息正文将原始字符串传递给您的帖子.
Alternate 2
Pass primitive strings to your post using the URI instead of the message body.
这篇关于Postman插件将值[FromBody]传递给post方法时的空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Postman插件将值[FromBody]传递给post方法时的空值
基础教程推荐
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 如果条件可以为空 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 将数据集转换为列表 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
