C# – 从403错误中获取响应正文

从URL请求数据时,我收到403错误。 这是预期的,我不会问如何纠正它。
将此URL直接粘贴到我的浏览器中时,我会获得一个基本信息串,用于描述拒绝权限的原因。
我需要通过我的C#代码读取这个基本错误消息,但是当发出请求时,System.Net.WebException(“远程服务器返回错误:(403)Forbidden。”)抛出错误,并且响应正文我无法使用。

是否可以简单地抓取页面的内容而不抛出exception? 相关的代码几乎是你所期望的,但无论如何它都在这里。

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sPageURL); try { //The exception is throw at the line below. HttpWebResponse response = (HttpWebResponse)(request.GetResponse()); //Snipped processing of the response. } catch(Exception ex) { //Snipped logging. } 

任何帮助,将不胜感激。 谢谢。

您正在寻找WebException.Response属性:

 catch(WebException ex) { var response = (HttpWebResponse)ex.Response; } 

这对我有用..

 HttpWebResponse httpResponse; try { httpResponse = (HttpWebResponse)httpReq.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { result = streamReader.ReadToEnd(); } } catch (WebException e) { Console.WriteLine("This program is expected to throw WebException on successful run." + "\n\nException Message :" + e.Message); if (e.Status == WebExceptionStatus.ProtocolError) { Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode); Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription); using (Stream data = e.Response.GetResponseStream()) using (var reader = new StreamReader(data)) { string text = reader.ReadToEnd(); Console.WriteLine(text); } } } catch (Exception e) { Console.WriteLine(e.Message); }