当我在 C# 中发布 JSON 帖子时,如何返回 HTTP 状态代码?



我不理解变量类型以及如何利用客户端检索http状态代码。client变量是一个标准的HttpClient对象。

所附图片是我试图检索状态代码期间的功能。任何帮助都将非常感激。[1]: https://i.stack.imgur.com/9iR3g.png

应该是很简单的

var client = new HttpClient();
var results = await client.GetAsync("https://stackoverflow.com");
Console.WriteLine(results.StatusCode);

您的问题是您没有获得响应对象。您正在获取响应正文的内容。

下面是一个示例代码:
void SimpleApiCall()
{ 
Uri endpoint = new Uri("https://www.7timer.info/bin/");
using var client = new HttpClient();
client.BaseAddress = endpoint;
// Get the response only here, and then get the content
// I'm using GetAwaiter().GetResult() because client.GetAsync() returns a Task and you're not using the async await since this is a button click event
var response = client.GetAsync("astro.php?lon=113.2&lat=23.1&ac=0&unit=metric&output=json&tzshift=0").GetAwaiter().GetResult();
// Status code will be available in the response
Console.WriteLine($"Status code: {response.StatusCode}");
// For the Reason phrase, it will be Ok for 200, Not Found for a 404 response...
Console.WriteLine($"Reason Phrase: {response.ReasonPhrase}");
// read the content of the response without the await keyword, use the .GetAwaiter().GetResult()
var content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
Console.WriteLine("Content:");
Console.WriteLine(content);
}

同样适用于PostAsync和所有其他操作…