Postman插件将值[FromBody]传递给post方法时的空值

Null value when Pass values [FromBody] to post method by Postman plugin(Postman插件将值[FromBody]传递给post方法时的空值)
本文介绍了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方法时的空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)