![](/img/trans.png)
[英]How can I get a Lambda using AWS Gateway to return HTTP error status code in C#
[英]C# - How to I get the HTTP Status Code from a http request
我有以下代码,作为 POST 请求按预期工作(给定正确的 URL 等)。 似乎我在读取状态代码时遇到了问题(我收到了成功的 201,根据该数字,我需要继续处理)。 知道如何获取状态代码吗?
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();
}
}
您的结果中有一个状态代码。
responseTask.Result.StatusCode
或者更好
var response = await client.SendAsync(request);
var statusCode = response.StatusCode;
如果您已经在一个async
函数中,它有助于避免使用ContinueWith
,因为您可以使用(更干净的) await
关键字。
如果您await
SendAsync
调用,您将获得一个HttpResponseMessage
对象,您可以从以下位置获取状态代码:
此外,将您的IDisposable
对象包装在using()
块中( HttpClient
除外 - 它应该是static
单例或更好,使用IHttpClientFactory
)。
不要将HttpClient.DefaultRequestHeaders
用于请求特定的标头,而是使用HttpRequestMessage.Headers
。
Connection: Keep-alive
标头将由HttpClientHandler
自动发送给您。Cache-control: no-cache
吗? 如果您使用 HTTPS,那么几乎可以保证不会有任何代理缓存导致任何问题 - HttpClient
也不使用 Windows Internet 缓存。Encoding.UTF8
因为它添加了前导字节顺序标记。 请改用私有UTF8Encoding
实例。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 );
}
}
}
您可以简单地检查响应的 StatusCode 属性:
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 对于返回状态代码本身是正确的,但如果您还想返回状态代码值(即 200、404)。 您可以执行以下操作:
var response = await client.SendAsync(request);
int statusCode = (int)response.StatusCode
以上将为您提供 int 200。
编辑:
您没有理由不能执行以下操作吗?
using (HttpResponseMessage response = await client.SendAsync(request))
{
// code
int code = (int)response.StatusCode;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.