[c#] The remote server returned an error: (403) Forbidden

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.

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?

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.

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


 }

This question is related to c#

The answer is


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 :

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

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.

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.


In my case I had to add both 'user agent' and 'default credentials = True'. I know this is pretty old, still wanted to share. Hope this helps. Below code is in powershell, but it should help others who are using c#.

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

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

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

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]";


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

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.


Setting:

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

and adding cookies than worked for me


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


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.