.net 使用确保成功状态代码和处理它抛出的 HttpRequestException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21097730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Usage of EnsureSuccessStatusCode and handling of HttpRequestException it throws
提问by G. Stoynev
What's the usage pattern of HttpResponseMessage.EnsureSuccessStatusCode()? It disposes of the Content of the message and throws HttpRequestException, but I fail to see how to programmatically handle it any differently than a generic Exception. For example, it doesn't include the HttpStatusCode, which would have been handy.
的使用模式是HttpResponseMessage.EnsureSuccessStatusCode()什么?它处理消息的内容并抛出HttpRequestException,但我看不出如何以编程方式处理它与通用Exception. 例如,它不包括HttpStatusCode,这本来很方便。
Is there any way of getting more info out of it? Could anyone show relevant usage pattern of both EnsureSuccessStatusCode()and HttpRequestException?
有没有办法从中获取更多信息?任何人都可以显示EnsureSuccessStatusCode()HttpRequestException 和 HttpRequestException 的相关使用模式吗?
回答by Timothy Shields
The idiomatic usage of EnsureSuccessStatusCodeis to concisely verify success of a request, when you don't want to handle failure cases in any specific way. This is especially useful when you want to quickly prototype a client.
EnsureSuccessStatusCode当您不想以任何特定方式处理失败情况时,的惯用用法是简洁地验证请求是否成功。当您想快速制作客户端原型时,这尤其有用。
When you decide you want to handle failure cases in a specific way, do notdo the following.
当您决定要以特定方式处理失败案例时,请不要执行以下操作。
var response = await client.GetAsync(...);
try
{
response.EnsureSuccessStatusCode();
// Handle success
}
catch (HttpRequestException)
{
// Handle failure
}
This throws an exception just to immediately catch it, which doesn't make any sense. The IsSuccessStatusCodeproperty of HttpResponseMessageis there for this purpose. Do the following instead.
这只是为了立即捕获它而抛出异常,这没有任何意义。的IsSuccessStatusCode属性HttpResponseMessage就是为此目的而存在的。请改为执行以下操作。
var response = await client.GetAsync(...);
if (response.IsSuccessStatusCode)
{
// Handle success
}
else
{
// Handle failure
}
回答by pajics
I don't like EnsureSuccessStatusCode as it doesn't return anything meaninful. That is why I've created my own extension:
我不喜欢EnsureSuccessStatusCode,因为它不返回任何有意义的东西。这就是为什么我创建了自己的扩展:
public static class HttpResponseMessageExtensions
{
public static async Task EnsureSuccessStatusCodeAsync(this HttpResponseMessage response)
{
if (response.IsSuccessStatusCode)
{
return;
}
var content = await response.Content.ReadAsStringAsync();
if (response.Content != null)
response.Content.Dispose();
throw new SimpleHttpResponseException(response.StatusCode, content);
}
}
public class SimpleHttpResponseException : Exception
{
public HttpStatusCode StatusCode { get; private set; }
public SimpleHttpResponseException(HttpStatusCode statusCode, string content) : base(content)
{
StatusCode = statusCode;
}
}
source code for Microsoft's EnsureSuccessStatusCode can be found here
可以在此处找到 Microsoft 的确保成功状态代码的源代码
Synchronous version based on SO link:
基于SO 链接的同步版本:
public static void EnsureSuccessStatusCode(this HttpResponseMessage response)
{
if (response.IsSuccessStatusCode)
{
return;
}
var content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
if (response.Content != null)
response.Content.Dispose();
throw new SimpleHttpResponseException(response.StatusCode, content);
}
What I don't like about IsSuccessStatusCode is that it is not "nicely" reusable. For example you can use library like pollyto repeat a request in case of network issue. In that case you need your code to raise exception so that polly or some other library can handle it...
我不喜欢 IsSuccessStatusCode 的地方在于它不能“很好地”重用。例如,您可以使用polly 之类的库在网络问题的情况下重复请求。在这种情况下,您需要您的代码引发异常,以便 polly 或其他一些库可以处理它...
回答by Sérgio Damasceno
I use EnsureSuccessStatusCode when I don't want to handle the Exception on the same method.
当我不想在同一方法上处理 Exception 时,我使用了 EnsureSuccessStatusCode。
public async Task DoSomethingAsync(User user)
{
try
{
...
var userId = await GetUserIdAsync(user)
...
}
catch(Exception e)
{
throw;
}
}
public async Task GetUserIdAsync(User user)
{
using(var client = new HttpClient())
{
...
response = await client.PostAsync(_url, context);
response.EnsureSuccesStatusCode();
...
}
}
The Exception thrown on GetUserIdAsync will be handled on DoSomethingAsync.
GetUserIdAsync 上抛出的异常将在 DoSomethingAsync 上处理。

