问题描述
为什么我总是从 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!