[英]C# - How to I get the HTTP Status Code from a http request
I have the below code, working as expected (given correct URL etc) as a POST request.我有以下代码,作为 POST 请求按预期工作(给定正确的 URL 等)。 Seems I have a problem reading the Status Code (I receive a successful 201, and based on that number I need to continue processing).
似乎我在读取状态代码时遇到了问题(我收到了成功的 201,根据该数字,我需要继续处理)。 Any idea how to get the status code?
知道如何获取状态代码吗?
static async Task CreateConsentAsync(Uri HTTPaddress, ConsentHeaders cconsentHeaders, ConsentBody cconsent)
{
HttpClient client = new HttpClient();
try
{
client.BaseAddress = HTTPaddress;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
client.DefaultRequestHeaders.Add("Connection", "keep-alive");
client.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
client.DefaultRequestHeaders.Add("otherHeader", myValue);
//etc. more headers added, as needed...
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress);
request.Content = new StringContent(JsonConvert.SerializeObject(cconsent, Formatting.Indented), System.Text.Encoding.UTF8, "application/json");
Console.WriteLine("\r\n" + "POST Request:\r\n" + client.DefaultRequestHeaders + "\r\nBody:\r\n" + JsonConvert.SerializeObject(cconsent, Formatting.Indented) + "\r\n");
await client.SendAsync(request).ContinueWith
(
responseTask =>
{
Console.WriteLine("Response: {0}", responseTask.Result + "\r\nBody:\r\n" + responseTask.Result.Content.ReadAsStringAsync().Result);
}
);
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Error in " + e.TargetSite + "\r\n" + e.Message);
Console.ReadLine();
}
}
There is a Status code in your Result.您的结果中有一个状态代码。
responseTask.Result.StatusCode
Or even better或者更好
var response = await client.SendAsync(request);
var statusCode = response.StatusCode;
It helps to avoid using ContinueWith
if you're already inside an async
function because you can use the (much cleaner) await
keyword.如果您已经在一个
async
函数中,它有助于避免使用ContinueWith
,因为您可以使用(更干净的) await
关键字。
If you await
the SendAsync
call you'll get a HttpResponseMessage
object you can get the status code from:如果您
await
SendAsync
调用,您将获得一个HttpResponseMessage
对象,您可以从以下位置获取状态代码:
Also, wrap your IDisposable
objects in using()
blocks (except HttpClient
- which should be a static
singleton or better yet, use IHttpClientFactory
).此外,将您的
IDisposable
对象包装在using()
块中( HttpClient
除外 - 它应该是static
单例或更好,使用IHttpClientFactory
)。
Don't use HttpClient.DefaultRequestHeaders
for request-specific headers, use HttpRequestMessage.Headers
instead.不要将
HttpClient.DefaultRequestHeaders
用于请求特定的标头,而是使用HttpRequestMessage.Headers
。
Connection: Keep-alive
header will be sent by HttpClientHandler
automatically for you. Connection: Keep-alive
标头将由HttpClientHandler
自动发送给您。Cache-control: no-cache
in the request?Cache-control: no-cache
吗? If you're using HTTPS then it's almost guaranteed that there won't be any proxy-caches causing any issues - and HttpClient
does not use the Windows Internet Cache either.HttpClient
也不使用 Windows Internet 缓存。Encoding.UTF8
because it adds a leading byte-order-mark.Encoding.UTF8
因为它添加了前导字节顺序标记。 Use a private UTF8Encoding
instance instead.UTF8Encoding
实例。.ConfigureAwait(false)
with every await
on code that does not run in a thread-sensitive context (such as WinForms and WPF).await
时始终使用.ConfigureAwait(false)
)。private static readonly HttpClient _httpClient = new HttpClient();
private static readonly UTF8Encoding _utf8 = new UTF8Encoding( encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true );
static async Task CreateConsentAsync( Uri uri, ConsentHeaders cconsentHeaders, ConsentBody cconsent )
{
using( HttpRequestMessage req = new HttpRequestMessage( HttpMethod.Post, uri ) )
{
req.Headers.Accept.Add( new MediaTypeWithQualityHeaderValue("*/*") );
req.Headers.Add("Cache-Control", "no-cache");
req.Headers.Add("otherHeader", myValue);
//etc. more headers added, as needed...
String jsonObject = JsonConvert.SerializeObject( cconsent, Formatting.Indented );
request.Content = new StringContent( jsonObject, _utf8, "application/json");
using( HttpResponseMessage response = await _httpClient.SendAsync( request ).ConfigureAwait(false) )
{
Int32 responseHttpStatusCode = (Int32)response.StatusCode;
Console.WriteLine( "Got response: HTTP status: {0} ({1})", response.StatusCode, responseHttpStatusCode );
}
}
}
You could simply check the StatusCode property of the response:您可以简单地检查响应的 StatusCode 属性:
https://docs.microsoft.com/en-us/previous-versions/visualstudio/hh159080(v=vs.118)?redirectedfrom=MSDN
https://docs.microsoft.com/en-us/previous-versions/visualstudio/hh159080(v=vs.118)?redirectedfrom=MSDN
static async void dotest(string url)
{
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode.ToString());
}
else
{
// problems handling here
Console.WriteLine(
"Error occurred, the status code is: {0}",
response.StatusCode
);
}
}
}
@AthanasiosKataras is correct for returning the status code itself but if you would also like to return the status code value (ie 200, 404). @AthanasiosKataras 对于返回状态代码本身是正确的,但如果您还想返回状态代码值(即 200、404)。 You can do the following:
您可以执行以下操作:
var response = await client.SendAsync(request);
int statusCode = (int)response.StatusCode
The above will give you the int 200.以上将为您提供 int 200。
EDIT:编辑:
Is there no reason why you cannot do the following?您没有理由不能执行以下操作吗?
using (HttpResponseMessage response = await client.SendAsync(request))
{
// code
int code = (int)response.StatusCode;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.