Post json data in body to web api(将正文中的 json 数据发布到 Web api)
问题描述
为什么我总是从 body 得到 null 值?我使用 fiddler 没有问题,但邮递员失败了.
I get always null value from body why ? I have no problem with using fiddler but postman is fail.
我有一个这样的 web api:
I have a web api like that:
[Route("api/account/GetToken/")]
[System.Web.Http.HttpPost]
public HttpResponseBody GetToken([FromBody] string value)
{
string result = value;
}
我的邮递员数据:
和标题:
推荐答案
WebAPI 正在按预期工作,因为您告诉它您正在发送此 json 对象:
WebAPI is working as expected because you're telling it that you're sending this json object:
{ "username":"admin", "password":"admin" }
然后您要求它将其反序列化为 string
这是不可能的,因为它不是有效的 JSON 字符串.
Then you're asking it to deserialize it as a string
which is impossible since it's not a valid JSON string.
解决方案 1:
如果您想接收 value
中的实际 JSON,则为:
If you want to receive the actual JSON as in the value of value
will be:
value = "{ "username":"admin", "password":"admin" }"
那么你需要在邮递员中设置请求正文的字符串是:
then the string you need to set the body of the request in postman to is:
"{ "username":"admin", "password":"admin" }"
解决方案 2(我假设这就是您想要的):
Solution 2 (I'm assuming this is what you want):
创建一个匹配 JSON 的 C# 对象,以便 WebAPI 可以正确反序列化它.
Create a C# object that matches the JSON so that WebAPI can deserialize it properly.
首先创建一个与您的 JSON 匹配的类:
First create a class that matches your JSON:
public class Credentials
{
[JsonProperty("username")]
public string Username { get; set; }
[JsonProperty("password")]
public string Password { get; set; }
}
然后在你的方法中使用这个:
Then in your method use this:
[Route("api/account/GetToken/")]
[System.Web.Http.HttpPost]
public HttpResponseBody GetToken([FromBody] Credentials credentials)
{
string username = credentials.Username;
string password = credentials.Password;
}
这篇关于将正文中的 json 数据发布到 Web api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将正文中的 json 数据发布到 Web api


- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 输入按键事件处理程序 2022-01-01