【问题标题】:The remote server returned an error: (403) Forbidden远程服务器返回错误:(403) Forbidden
【发布时间】:2013-05-24 12:30:45
【问题描述】:

我编写的应用程序运行良好几个月,在过去的几天里,我只在已安装的版本上收到以下错误。

如果我在 VS 中运行源代码,一切正常。此外,bin 文件夹中的 .exe 工作正常。只有安装的版本会产生错误,如果我重新编译并重新安装,我会得到同样的错误。

我对造成这种情况的原因感到有些困惑,并希望得到一些指示。似乎没有返回通过 IE 的 WebRequest 响应,但我很难理解为什么它在 VS 中可以正常工作而没有任何错误。是否有任何新的 IE 安全措施/政策可能导致这种情况?

到目前为止我尝试过的事情包括:

  • 禁用所有防病毒和防火墙
  • 以管理员身份运行

例外:

Exception: System.Windows.Markup.XamlParseException: The invocation of the constructor on type 'XApp.MainWindow' that matches the specified binding constraints threw an exception. ---> System.Net.WebException: The remote server returned an error: (403) Forbidden.
   at System.Net.HttpWebRequest.GetResponse()
   at XApp.HtmlRequest.getHtml(Uri uri) in J:\Path\MainWindow.xaml.cs:line 3759
   at XApp.MainWindow.GetLinks() in J:\Path\MainWindow.xaml.cs:line 2454
   at XApp.MainWindow..ctor() in J:\Path\MainWindow.xaml.cs:line 124
   --- End of inner exception stack trace ---
   at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
   at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
   at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
   at System.Windows.Application.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc)
   at System.Windows.Application.LoadComponent(Uri resourceLocator, Boolean bSkipJournaledProperties)
   at System.Windows.Application.DoStartup()
   at System.Windows.Application.<.ctor>b__1(Object unused)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
Exception: System.Net.WebException: The remote server returned an error: (403) Forbidden.
   at System.Net.HttpWebRequest.GetResponse()
   at XApp.HtmlRequest.getHtml(Uri uri) in J:\Path\MainWindow.xaml.cs:line 3759
   at XApp.MainWindow.GetLinks() in J:\Path\MainWindow.xaml.cs:line 2454
   at XApp.MainWindow..ctor() in J:\Path\MainWindow.xaml.cs:line 124

编辑:

这是作为独立应用程序安装的。当我以管理员身份运行时,我打开了程序文件夹并以管理员身份而不是快捷方式运行 exe。

导致问题的代码是这样的

private void GetLinks()
{
    //Navigate to front page to Set cookies
    HtmlRequest htmlReq = new HtmlRequest();

    OLinks = new Dictionary<string, List<string>>();

    string Url = "http://www.somesite.com/somepage";
    CookieContainer cookieJar = new CookieContainer();
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
    request.CookieContainer = cookieJar;

    request.Accept = @"text/html, application/xhtml+xml, */*";
    request.Referer = @"http://www.somesite.com/";
    request.Headers.Add("Accept-Language", "en-GB");
    request.UserAgent = @"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)";
    request.Host = @"www.somesite.com";

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    String htmlString;
    using (var reader = new StreamReader(response.GetResponseStream()))
    {
        htmlString = reader.ReadToEnd();
    }

    //More Code


 }

【问题讨论】:

  • 首先你的代码是什么?然后,如果我是你,我会尝试使用 Fiddler 监控 HTTP 消息,并比较工作和不工作的请求。
  • 您如何运行“已安装版本” - 作为服务还是常规控制台/桌面应用程序?您应该尝试验证应用程序在哪个用户上下文中运行。您能否详细说明您为以管理员身份运行应用程序所做的工作?请提供有关您的应用程序架构的更多详细信息 - 建立了哪些连接。这是服务器还是客户端?

标签: c#


【解决方案1】:

添加以下行:

request.UseDefaultCredentials = true;

这将使应用程序使用登录用户的凭据来访问该站点。如果它返回 403,显然它正在等待身份验证。

您(现在?)也有可能在您和远程站点之间有一个身份验证代理。在这种情况下,请尝试:

request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;

希望这会有所帮助。

【讨论】:

  • 抱歉耽搁了,我只是在测试。您的第一个建议已经解决了问题。非常感谢!
【解决方案2】:

看起来问题是基于服务器端的。

我的情况是我使用贝宝服务器,建议的答案都没有帮助,但http://forums.iis.net/t/1217360.aspx?HTTP+403+Forbidden+error

我遇到了这个问题,刚刚收到 Paypal 技术人员的回复。 添加这将解决 403 问题。 HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.UserAgent = "[any words that is more than 5 characters]";

【讨论】:

  • 这是我在尝试使用 GitHub API 时遇到的“禁止”问题的解决方案。在我偶然发现这篇文章之前花了几个小时搜索。
  • .UserAgent 是我在生产服务器上的。我想我一定是在没有指定代理的情况下将 IIS 设置为禁止请求。
  • 同上 Spotify ATOM 提要
  • 我也是在从 GitHub API 获得 403 后到达这里的。后来我找到了这个文档,其中 GitHub 声明需要 UserAgent:developer.github.com/v3/#user-agent-required
【解决方案3】:

这是一个权限错误。您的 VS 可能使用提升的帐户或与使用已安装版本的用户不同的用户帐户运行。

检查您的 IIS 权限并查看哪些帐户可以访问您正在访问的资源可能很有用。与您使用的帐户和已安装版本使用的帐户交叉引用。

【讨论】:

  • 管理员账户是否对接收请求的网络服务器有权限?请记住 MyLocalPC\Administrator 和 server\Administrator 不是同一个帐户
【解决方案4】:

我们应该使用证书中给出的名称访问该网站。

【讨论】:

    【解决方案5】:

    就我而言,我必须同时添加“用户代理”和“默认凭据 = True”。我知道这已经很老了,仍然想分享。希望这可以帮助。下面的代码在 powershell 中,但它应该可以帮助其他使用 c# 的人。

    [System.Net.HttpWebRequest] $req = [System.Net.HttpWebRequest]::Create($uri)
    $req.UserAgent = "BlackHole"
    $req.UseDefaultCredentials = $true
    

    【讨论】:

    • 在我的情况下,我必须添加以下值并使其工作:webReq.UseDefaultCredentials = true; webReq.UserAgent = "我的 API 代理"; webReq.Referer = example.com>;
    【解决方案6】:
        private class GoogleShortenedURLResponse
        {
            public string id { get; set; }
            public string kind { get; set; }
            public string longUrl { get; set; }
        }
    
        private class GoogleShortenedURLRequest
        {
            public string longUrl { get; set; }
        }
    
        public ActionResult Index1()
        {
            return View();
        }
    
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ShortenURL(string longurl)
        {
            string googReturnedJson = string.Empty;
            JavaScriptSerializer javascriptSerializer = new JavaScriptSerializer();
    
            GoogleShortenedURLRequest googSentJson = new GoogleShortenedURLRequest();
            googSentJson.longUrl = longurl;
            string jsonData = javascriptSerializer.Serialize(googSentJson);
    
            byte[] bytebuffer = Encoding.UTF8.GetBytes(jsonData);
    
            WebRequest webreq = WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url");
            webreq.Method = WebRequestMethods.Http.Post;
            webreq.ContentLength = bytebuffer.Length;
            webreq.ContentType = "application/json";
    
            using (Stream stream = webreq.GetRequestStream())
            {
                stream.Write(bytebuffer, 0, bytebuffer.Length);
                stream.Close();
            }
    
            using (HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse())
            {
                using (Stream dataStream = webresp.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(dataStream))
                    {
                        googReturnedJson = reader.ReadToEnd();
                    }
                }
            }
    
            //GoogleShortenedURLResponse googUrl = javascriptSerializer.Deserialize<googleshortenedurlresponse>(googReturnedJson);
    
            //ViewBag.ShortenedUrl = googUrl.id;
            return View();
        }
    

    【讨论】:

    • 不要在没有解释的情况下给出答案。请解释你的推荐。这是一个可以回答问题的大代码块,但应该与一些细节配对。
    【解决方案7】:

    这可能不会帮助太多人,但这是我的情况:我正在使用 Jira Rest Api 并且正在使用我的个人凭据(我用来登录 Jira 的凭据)。我已经更新了我的 Jira 密码,但忘记在我的代码中更新它们。我收到 403 错误,我尝试在代码中更新我的密码,但仍然收到错误。

    解决方案:我尝试登录 Jira(从他们的登录页面),我必须输入文本以证明我不是机器人。之后,我再次尝试从代码中,它的工作。要点:服务器可能已将您拒之门外。

    【讨论】:

      【解决方案8】:

      在我的例子中,我记得前段时间在防火墙中为这个地址创建了一个洞,所以我不得不在配置文件中的绑定上设置 useDefaultWebProxy="false",就好像默认是使用代理一样如果未指定 useDefaultWebProxy。

      【讨论】:

        【解决方案9】:

        设置:

        request.Referer = @"http://www.somesite.com/";
        

        并添加 cookies 比对我有用

        【讨论】:

        • 你是如何动态添加cookie的?
        【解决方案10】:

        就我而言,我不得不在循环中重复调用 API,这导致我的系统停止返回 403 Forbidden Error。由于我的 API 提供程序不允许在几毫秒内来自同一个客户端的多个请求,我不得不使用至少 1 秒的延迟:

        foreach (var it in list)
        {
            Thread.Sleep(1000);
            // Call API
        }
        

        【讨论】:

          【解决方案11】:

          刚刚出现这个错误。问题是客户端计算机在 Windows 中的日期/时间错误。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-07-13
            • 1970-01-01
            相关资源
            最近更新 更多