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
基础教程推荐
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 如果条件可以为空 2022-01-01
- 将数据集转换为列表 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
