WebException的抑制

问题描述

当C#WebClient中的http状态代码为500时,是否可以抑制WebException的发生? WebException由StackTrace创建,这会降低系统速度。如果WebExceptions频繁发生,这尤其严重。

解决方法

http客户端很多,其中一个是WebClient。 WebClient是设计的引发异常。没有办法让人们抛出异常,就像人们想要的那样。

它的前身HttpWebRequest / HttpWebResponsealso does this

如果您不想捕获异常,则需要使用其他客户端。

HttpClient doesn't throw exceptions based on the returned status code,这是一个选择。

您可以使用Flurl代替uses HttpClient under the hood。添加error handling方法.AllowHttpStatus("500")