[英]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.