将正文中的json数据发布到Web API [英] Post json data in body to web api
问题描述
我总是从体内得到空值,为什么?
我没有使用提琴手的问题,但是邮递员失败了。
I get always null value from body why ? I have no problem with using fiddler but postman is fail.
我有这样的网络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;
}
我的邮递员数据:
My postman data:
和标头:
and header:
推荐答案
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:
如果要接收实际的JSON,如 value
的值将是:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!