1. 程式人生 > >C#在異常中獲取HttpStatusCode用法

C#在異常中獲取HttpStatusCode用法

HttpStatusCode用法
原來我的寫法是:

            catch (Exception ex)
            {

                msg = ex.ToString();

                return false;
            }

發現這麼寫沒法獲取到status code,所以參考該文章,取WebException e,即可。

catch (WebException e)
{
       string status = null;
       HttpWebResponse response = (HttpWebResponse)e.Response
; if (response.StatusCode == HttpStatusCode.NotFound) status = "404"; if (response.StatusCode == HttpStatusCode.InternalServerError) status = "500"; if (response.StatusCode == HttpStatusCode.BadGateway) status = "502"; }