How to get status code from webclient?

前端 未结 10 1878
轮回少年
轮回少年 2020-11-29 04:03

I am using the WebClient class to post some data to a web form. I would like to get the response status code of the form submission. So far I\'ve found out how

10条回答
  •  北海茫月
    2020-11-29 05:00

    Erik's answer doesn't work on Windows Phone as is. The following does:

    class WebClientEx : WebClient
    {
        private WebResponse m_Resp = null;
    
        protected override WebResponse GetWebResponse(WebRequest Req, IAsyncResult ar)
        {
            try
            {
                this.m_Resp = base.GetWebResponse(request);
            }
            catch (WebException ex)
            {
                if (this.m_Resp == null)
                    this.m_Resp = ex.Response;
            }
            return this.m_Resp;
        }
    
        public HttpStatusCode StatusCode
        {
            get
            {
                if (m_Resp != null && m_Resp is HttpWebResponse)
                    return (m_Resp as HttpWebResponse).StatusCode;
                else
                    return HttpStatusCode.OK;
            }
        }
    }
    

    At least it does when using OpenReadAsync; for other xxxAsync methods, careful testing would be highly recommended. The framework calls GetWebResponse somewhere along the code path; all one needs to do is capture and cache the response object.

    The fallback code is 200 in this snippet because genuine HTTP errors - 500, 404, etc - are reported as exceptions anyway. The purpose of this trick is to capture non-error codes, in my specific case 304 (Not modified). So the fallback assumes that if the status code is somehow unavailable, at least it's a non-erroneous one.

提交回复
热议问题