问题描述
我在 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方法时的空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!