C# - 从403错误获取响应正文 [英] C# - Getting the response body from a 403 error

查看:1371
本文介绍了C# - 从403错误获取响应正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从URL请求数据时收到一个403错误。这是预料之中,我不问如何纠正它。

当直接粘贴此URL到我的浏览器,我得到的描述为什么权限被拒绝信息的基本字符串。

我需要通过我的C#code阅读这个基本的错误信息,但是当请求时,一个System.Net.WebException(远程服务器返回错误:(403)禁止)引发错误,并响应主体不可用在我身上。

I'm receiving a 403 error when requesting data from a URL. This is expected and I'm not asking how to correct it.
When pasting this URL directly into my browser, I get a basic string of information describing why permission is denied.
I need to read this basic error message via my C# code, however when the request is made, a System.Net.WebException ("The remote server returned an error: (403) Forbidden.") error is thrown, and the response body is unavailable to me.

是否有可能简单地抓取无异常的页面的内容被抛出?
有关code是pretty多少你所期望的,但在这里它是无论如何。

Is it possible to simply grab the content of the page without the exception being thrown? The relevant code is pretty much what you'd expect, but here it is anyway.

   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.
   }

任何帮助将是AP preciated。谢谢你。

Any help would be appreciated. Thanks.

推荐答案

您正在寻找的 WebException.Response 属性:

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

这篇关于C# - 从403错误获取响应正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆