Post json body 中的数据到网络 api

Post json data in body to web api

我总是从 body 得到空值,为什么? 我使用 fiddler 没有问题,但是 postman 失败了。

我有一个这样的网站 api:

    [Route("api/account/GetToken/")]
    [System.Web.Http.HttpPost]
    public HttpResponseBody GetToken([FromBody] string value)
    {
        string result = value;
    }

我的邮递员数据:

和header:

您正在发布一个对象并试图将其绑定到一个字符串。 相反,创建一个类型来表示该数据:

public class Credentials
{
    public string Username { get; set; }
    public string Password { get; set; }
}

[Route("api/account/GetToken/")]
[System.Web.Http.HttpPost]
public HttpResponseBody GetToken([FromBody] Credentials value)
{
    string result = value.Username;
}

WebAPI 正在按预期工作,因为您告诉它您正在发送这个 json 对象:

{ "username":"admin", "password":"admin" }

然后你要求它将它反序列化为 string 这是不可能的,因为它不是有效的 JSON 字符串。

解决方案一:

如果您想接收实际的 JSON,如 value 的值将是:

value = "{ \"username\":\"admin\", \"password\":\"admin\" }"

那么你需要在邮递员中设置请求正文的字符串是:

"{ \"username\":\"admin\", \"password\":\"admin\" }"

解决方案 2(我假设这就是您想要的):

创建一个匹配 JSON 的 C# 对象,以便 WebAPI 可以正确反序列化它。

首先创建一个 class 匹配您的 JSON:

public class Credentials
{
    [JsonProperty("username")]
    public string Username { get; set; }

    [JsonProperty("password")]
    public string Password { get; set; }
}

然后在你的方法中使用这个:

[Route("api/account/GetToken/")]
[System.Web.Http.HttpPost]
public HttpResponseBody GetToken([FromBody] Credentials credentials)
{
    string username = credentials.Username;
    string password = credentials.Password;
}