System.Net.WebClient请求获取403 Forbidden但浏览器不支持Apache服务器

时间:2010-02-23 04:28:13

标签: .net apache http-headers webclient http-status-code-403

奇怪的是,我正在尝试阅读< Head>很多不同网站的部分,以及一种特定类型的服务器,Apache,有时会禁止代码403。并非所有的apache服务器都这样做,因此它可能是配置设置或服务器的特定版本。

当我使用网络浏览器(例如Firefox)检查网址时,页面加载正常。代码sorta如下所示:

var client = new WebClient();
var stream = client.OpenRead(new Uri("http://en.wikipedia.org/wiki/Barack_Obama"));

通常,403是一种访问权限失败的东西,但这些通常是不安全的页面。我认为Apache正在过滤请求标头中的某些东西,因为我不打算创建任何东西。

也许知道更多关于Apache的人可以给我一些关于标题中缺少什么的想法。我想保持标头尽可能小,以尽量减少带宽。

谢谢

4 个答案:

答案 0 :(得分:10)

尝试设置UserAgent标头:

string _UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
client.Headers.Add(HttpRequestHeader.UserAgent, _UserAgent);

答案 1 :(得分:4)

我有类似的问题,下面的设置解决了它

Client.Headers["Accept"] = "application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
Client.Headers["User-Agent"] ="Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; MDDC)";

答案 2 :(得分:1)

这可能是UserAgent标题的问题,正如“thedugas”所说,或实际上浏览器默认配置的任何内容。例如,可能是不使用浏览器正在使用的代理服务器,或者不使用代理服务器的正确凭据。这些东西可能已经配置到浏览器中,所以你不知道它们需要完成。

答案 3 :(得分:0)

我遇到了同样的问题,答案并不明显。我找到了嗅探网络通信的解决方案。当Apache提供其“ Testing 1 2 3 ...”页面时,它将返回带有403禁止代码的html。浏览器将忽略获取代码并显示页面,但是de WebClient返回错误消息。解决方案是读取“尝试捕获”语句中的响应。这是我的代码:

            Dim Retorno As String = ""
            Dim Client As New SiteWebClient
            Client.Headers.Add("User-Agent", "Mozilla/ 5.0(Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " &
                               "(KHTML, Like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134")
            Client.Headers.Add("Accept-Language", "pt-BR, pt;q=0.5")
            Client.Headers.Add("Accept", "Text/ html, application / xhtml + Xml, application / Xml;q=0.9,*/*;q=0.8")
            Try
                Retorno = Client.DownloadString("http://" & HostName & SitePath)
            Catch ex As Exception
                If ex.GetType = GetType(System.Net.WebException) Then
                    Try
                        Dim Exception As System.Net.WebException = ex
                        Dim Resposta As System.Net.HttpWebResponse = Exception.Response
                        Using WebStream As New StreamReader(Resposta.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"))
                            Retorno = WebStream.ReadToEnd
                        End Using
                    Catch ex1 As Exception

                    End Try
                End If
            End Try

在“尝试”语句之后,无论服务器返回的错误代码是什么,Retorno都将包含来自服务器的HTML响应。

标头对此行为没有影响。