的EnsureSuccessStatus $ C $的Htt的prequestException c和操作使用它抛出抛出、操作、使用它、EnsureSuccessStatus

2023-09-03 12:26:47 作者:小三縱然心碎也要笑的甜美

什么是的Htt presponseMessage.EnsureSuccessStatus code的使用模式()?其配置消息的内容,并引发的Htt prequestException ,但我看不出如何以编程方式处理任何不同于一般的异常。例如,它不包括的HTTPStatus code ,这将是得心应手。

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.

有没有办法获得更多的信息出来的呢?任何人都可以同时显示相关的使用模式 EnsureSuccessStatus code()和Htt的prequestException?

Is there any way of getting more info out of it? Could anyone show relevant usage pattern of both EnsureSuccessStatusCode() and HttpRequestException?

推荐答案

的习惯用法 EnsureSuccessStatus code 是简洁验证请求成功,当你不想处理失败的情况下,在任何特定的方式。当你想快速原型客户端,这是特别有用的。

The idiomatic usage of EnsureSuccessStatusCode is 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.

当你决定要处理失败的情况下以特定的方式,不要做到以下几点。

When you decide you want to handle failure cases in a specific way, do not do the following.

var response = await client.GetAsync(...);
try
{
    response.EnsureSuccessStatusCode();
    // Handle success
}
catch (HttpRequestException)
{
    // Handle failure
}

这将引发异常只是为了马上抓住它,它没有任何意义。 的Htt presponseMessage IsSuccessStatus code 属性是有这个目的。请执行以下操作来代替。

This throws an exception just to immediately catch it, which doesn't make any sense. The IsSuccessStatusCode property of HttpResponseMessage is there for this purpose. Do the following instead.

var response = await client.GetAsync(...);
if (response.IsSuccessStatusCode)
{
    // Handle success
}
else
{
    // Handle failure
}
 
精彩推荐
图片推荐