通过Postman插件将[FromBody]值传递给post方法时为空值 [英] Null value when Pass values [FromBody] to post method by Postman plugin

查看:1647
本文介绍了通过Postman插件将[FromBody]值传递给post方法时为空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ASP.net Web API中使用api控制器,我需要通过[FromBody]类型将值传递给发布方法。.

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 插件,但是当发送到post方法时, name 的值始终为 null ..按照此图像:

i use Postman plugin but when send to post method value of name always is null.. follow this image:

和Post方法:
< a href = https://i.stack.imgur.com/rYdcI.png rel = noreferrer>

为什么会这样?!

推荐答案

您不能使用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方法时为空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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