API 控制器无法从 POST 正文读取 Json

Dan*_*ndy 1 c# asp.net-core asp.net-core-webapi asp.net-core-2.0

背景

我将身体中的 JSON 发送到我的 API 控制器,但不断收到以下错误。

{"":["解析值时遇到意外字符:{.路径'',第1行,位置1。"]}

我的 HTTP 请求

HttpClient client = new HttpClient();
HttpRequest httpRequest;
HttpResponseMessage httpResponse = null;
httpRequest = new HttpRequest("", HostnameTb.Text, null);

var values = new Dictionary<string, string>
{
    { "APIKey", APIKeyTb.Text }
};

string json = JsonConvert.SerializeObject(values);
StringContent content = new StringContent(json.ToString(), Encoding.UTF8, "application/json");
httpResponse = client.PostAsync(HostnameTb.Text, content).Result;

var responseString = await httpResponse.Content.ReadAsStringAsync();
Run Code Online (Sandbox Code Playgroud)

我的控制器看起来像这样。

[HttpPost]
public void Post([FromBody] string value)
{
  //Never gets here.
}
Run Code Online (Sandbox Code Playgroud)

体内的 Json。

{"APIKey":"1283f0f8..."}

我更喜欢使用 .Net Core[From Body]功能,而不是手动获取内容。

我希望 JSON 字符串在 stringValue参数中可用。

我错过了什么?

Tom*_*han 7

ASP.NET Core 尝试{"APIKey":"1283f0f8..."}从 JSON反序列化为一个string值,但失败了,因为它期望输入是有效的 JSON 字符串。

换句话说,如果你的身体是"{\"APIKey\":\"1283f0f8...\"}"你所期望的,那么你会在输入变量中有 JSON 字符串。

为了在APIKey不更改 HTTP 请求的情况下获取值,请创建一个输入类型:

public class Input
{
    public string ApiKey { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

并将其用作控制器操作的输入:

[HttpPost]
public void Post([FromBody] Input input)
{
    var apiKey = input.ApiKey;
    // etc
}
Run Code Online (Sandbox Code Playgroud)

或者,更改您的 HTTP 请求以发送string

// ...
var content = new StringContent(JsonConvert.SerializeObject(json), Encoding.UTF8, "application/json");
// ...
Run Code Online (Sandbox Code Playgroud)

注意使用JsonConvert.SerializeObject()代替ToString(); "foo".ToString()依然只是"foo",随心所欲"\"foo\""