我有一個Web API,當傳入的請求無效時,API會發回一個HttpStatusCode.BadRequest,並且API還會將一個CorrelationId添加到Response的HttpHeader中。類似下面從HttpRequestException中獲取HttpHeaders?
public class ValidateRequestAttribute : ActionFilterAttribute
{
public ValidateRequestAttribute()
{
}
public override void OnActionExecuting(ActionExecutingContext context)
{
if (context.ModelState.IsValid == false)
{
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
context.HttpContext.Response.Headers.Add("x-correlationid", "someid");
context.Result = new ContentResult()
{
Content = "bad request."
};
}
}
}
在客戶端IM使用HttpClient的訪問API。我不知道客戶端如何在這裏檢索HttpStatusCode和HttpHeader。這裏是我的客戶端代碼
public bool Process(url)
{
bool result = false;
try
{
Task.Run(async() => await _httpClient.GetStringAsync(url).ConfigureAwait(false)).Result;
}
catch (Exception ex)
{
if(ex is AggregateException)
{
var aggregateException = ex as AggregateException;
foreach(var innerException in aggregateException.InnerExceptions)
{
if (innerException is HttpRequestException)
{
var httpRequestException = innerException as HttpRequestException;
// how do i get StatusCode and HttpHeader values here??
}
}
}
}
return result;
}
我已經走過了SO發佈here和MSDN文章here也斯蒂芬·克利裏的文章here
儘管其建議,使異步一路下來,我這種情況下,客戶端和API都彼此斷開連接並且客戶端是同步的。請注意,客戶端的Process方法是同步方法。
兩個問題1>我們不必使用'ConfigureAwait(false)'來避免死鎖。類似.'_httpClient.GetAsync(_appsettings.GetInProgressWorkunitsUrl).ConfigureAwait(false).GetAwaiter()。GetResult();'。見Stephen Cleary上面的文章。 2>當StatusCode確定時,如何獲得響應字符串 – LP13
對不起,更新了答案 – peco