在 Web API 控制器中发现 HTTP PUT 请求正文为空

HTTP PUT Request Body Found Null In Web API Controller

我正在尝试使用 HTTP 动词 [HttpPut] 发送请求,该请求已到达我的控制器,但我发送的参数是 Null。已经看到很多堆栈溢出相同的线程并尝试但无法弄清楚......很奇怪!

Class 我已经连载了

Content requestContent = new Content();
requestContent.Name = "Name";
requestContent.Value = "Value";

这是我的请求正文

private readonly HttpClient _httpClient;

public GetAzureResponseClient(HttpClient httpClient)
{
    _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
}

var requestBody = JsonConvert.SerializeObject(requestContent); 
var uri = new Uri("http://localhost:64288/api/ConnectUs/TestMethod");
var response = _httpClient.PutAsJsonAsync(uri, new StringContent(requestBody, Encoding.UTF8, "application/json")).Result;
client.DefaultRequestHeaders.Add("Authorization", "Basic" + "YourAuthKey");
var responseFromServer = await response.Content.ReadAsStringAsync();

我的网站API控制器

public ActionResult<Content> TestMethod([FromBody]Content param)

您不需要额外的序列化,您必须使用 'await' 调用 Async 方法。

        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Add("Authorization", "Basic" + "YourAuthKey");
        var uri = new Uri("http://localhost:64288/api/ConnectUs/TestMethod");
        var response = await client.PutAsJsonAsync(uri, requestContent);
        var responseFromServer = await response.Content.ReadAsStringAsync();

https://docs.microsoft.com/en-us/previous-versions/aspnet/hh944690(v%3Dvs.118)

PutAsJsonAsync 将序列化给定类型 T 的对象,请改用 PutAsync

https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.putasync?view=netframework-4.8

使用 PutAsJsonAsync 时,您不需要将对象重新包装为 JSON:

HttpClient client = new HttpClient();
var uri = new Uri("http://localhost:64288/api/ConnectUs/TestMethod");
var response = await client.PutAsJsonAsync(uri, requestContent); // LOOK HERE
client.DefaultRequestHeaders.Add("Authorization", "Basic" + "YourAuthKey");
var responseFromServer = await response.Content.ReadAsStringAsync();