C# 远程服务器返回错误:(403) Forbidden

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16735042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:47:32  来源:igfitidea点击:

The remote server returned an error: (403) Forbidden

c#

提问by user3357963

I've written an app that has worked fine for months, in the last few days I've been getting the error below on the installed version only.

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

If I run the source code in VS everything works fine. Also, the .exe in the bin folders work fine. It's only the installed version which generates the error, if I recompile and reinstall I get the same error.

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

I'm a bit stumped as to what's causing this and hoped for a few pointers. It seems to be a WebRequest response through IE is not being returned but I'm stumped as to why it works fine in VS without any errors. Are there any new IE security measures/polices that may cause this?

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

Things I've tried so far include:

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

  • Disabled all AntiVirus & Firewall
  • Run as Administrator
  • 禁用所有防病毒和防火墙
  • 以管理员身份运行

The Exception:

例外:

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

EDIT:

编辑:

This is installed as a standalone app. When I've run as Administrator, I've opened the program folder and run the exe as administrator rather than the shortcut.

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

The code that causes the issue is this

导致问题的代码是这样的

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


 }

采纳答案by x0n

Add the following line:

添加以下行:

request.UseDefaultCredentials = true;

This will let the application use the credentials of the logged in user to access the site. If it's returning 403, clearly it's expecting authentication.

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

It's also possible that you (now?) have an authenticating proxy in between you and the remote site. In which case, try:

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

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

Hope this helps.

希望这可以帮助。

回答by James

Its a permissions error. Your VS probably runs using an elevated account or different user account than the user using the installed version.

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

It may be useful to check your IIS permissions and see what accounts have access to the resource you are accessing. Cross reference that with the account you use and the account the installed versions are using.

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

回答by Budda

Looks like problem is based on a server side.

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

Im my case I worked with paypal server and neither of suggested answers helped, but http://forums.iis.net/t/1217360.aspx?HTTP+403+Forbidden+error

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

I was facing this issue and just got the reply from Paypal technical. Add this will fix the 403 issue. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.UserAgent = "[any words that is more than 5 characters]";

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

回答by Sanesh

    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();
    }

回答by W. Boldt

This probably won't help too many people, but this was my case: I was using the Jira Rest Api and was using my personal credentials (the ones I use to log into Jira). I had updated my Jira password but forgot to update them in my code. I got the 403 error, I tried updating my password in the code but still got the error.

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

The solution: I tried logging into Jira (from their login page) and I had to enter the text to prove I wasn't a bot. After that I tried again from the code and it worked. Takeaway: The server may have locked you out.

解决方案:我尝试登录 Jira(从他们的登录页面),我必须输入文本以证明我不是机器人。之后,我从代码中再次尝试,并且成功了。要点:服务器可能已将您锁定。

回答by Roger Perkins

In my case I remembered that a hole in the firewall was created for this address some time ago, so I had to set useDefaultWebProxy="false" on the binding in the config file, as if the default was to use the proxy if useDefaultWebProxy is not specified.

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

回答by anju

Setting:

环境:

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

and adding cookiesthan worked for me

添加cookies比对我有用

回答by Vishnu Prasanth

We should access the website using the name given in the certificate.enter image description here

我们应该使用证书中给出的名称访问该网站。在此处输入图片说明

回答by Bilal Ahmed

In my case, I had to call an API repeatedly in a loop, which resulted in halt of my system returning a 403 Forbidden Error. Since my API provider does not allow multiple requests from the same client within milliseconds, I had to use a delay of 1 second at least :

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

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