如何在使用HttpClient.GetAsync()时确定404响应状态
我试图确定HttpClient
的GetAsync
方法在使用C#和.NET 4.5的404错误的情况下返回的response
。
目前我只能说出错误已经发生而不是错误的状态,如404或超时。
目前我的代码我的代码如下所示:
static void Main(string[] args) { dotest("https://error.123"); Console.ReadLine(); } static async void dotest(string url) { HttpClient client = new HttpClient(); HttpResponseMessage response = new HttpResponseMessage(); try { response = await client.GetAsync(url); if (response.IsSuccessStatusCode) { Console.WriteLine(response.StatusCode.ToString()); } else { // problems handling here string msg = response.IsSuccessStatusCode.ToString(); throw new Exception(msg); } } catch (Exception e) { // .. and understanding the error here Console.WriteLine( e.ToString() ); } }
我的问题是我无法处理exception并确定其状态以及出错的其他详细信息。
我如何正确处理exception并解释发生了什么错误?
您只需检查响应的StatusCode
属性:
上述就是C#学习教程:如何在使用HttpClient.GetAsync()时确定404响应状态分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
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 ); } } }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1012538.html