使用WebClient發送請求,若是返回的狀態碼不是2xx或3xx,那麼默認狀況下會拋出異常,
那如何才能獲取到請求返回的內容呢?ui
能夠經過try catch獲取到WebException類型的異常;編碼
[HttpGet("test")] public ActionResult test() { Response.StatusCode = 401; return Content("test"); }
public static string WebClientGetRequest(string url) { try { using (WebClient client = new WebClient()) { //設置編碼格式 client.Encoding = System.Text.Encoding.UTF8; //獲取數據 var result = client.DownloadString(url); return result; } } catch (WebException ex) { using (HttpWebResponse hr = (HttpWebResponse)ex.Response) { int statusCode = (int)hr.StatusCode; StringBuilder sb = new StringBuilder(); StreamReader sr = new StreamReader(hr.GetResponseStream(), Encoding.UTF8); sb.Append(sr.ReadToEnd()); Console.WriteLine("StatusCode:{0},Content:{1}", statusCode, sb);// StatusCode:401,Content:test } return ""; } }
方法二:捕獲 Exception 異常,而後再判斷異常類型;url
public static string WebClientGetRequest(string url) { try { using (WebClient client = new WebClient()) { //設置編碼格式 client.Encoding = System.Text.Encoding.UTF8; //獲取數據 var result = client.DownloadString(url); return result; } } catch (WebException ex) { if (ex.GetType().Name == "WebException") { WebException we = (WebException)ex; using (HttpWebResponse hr = (HttpWebResponse)we.Response) { int statusCode = (int)hr.StatusCode; StringBuilder sb = new StringBuilder(); StreamReader sr = new StreamReader(hr.GetResponseStream(), Encoding.UTF8); sb.Append(sr.ReadToEnd()); Console.WriteLine("StatusCode:{0},Content:{1}", statusCode, sb);// StatusCode:401,Content:test } } return ""; } }