35

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


 }
  • 1
    First of all what is your code? Then, if I were you, I would try to monitor the HTTP messages using Fiddler, and compare working and not working requests. – Steve B May 24 '13 at 12:33
  • 1
    How do you run your "installed version" - as a Service or is it a regular console/desktop application? You should try to verify under which user context the application is run. Can you elaborate on exactly what you did to run your application as Administrator? Please provide a little more detail about your application architecture - what connections are established. Is this a server or client? – Marcus May 24 '13 at 12:37

12 Answers12

27

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

Mikaël Mayer
  • 10,425
  • 6
  • 64
  • 101
Budda
  • 18,015
  • 33
  • 124
  • 206
  • 2
    This was the solution to the "Forbidden" issue that I encountered when trying to use the GitHub API. It took several hours of searching before I stumbled across this post. – Marc Clifton Feb 20 '15 at 12:42
  • 1
    .UserAgent was it for me on a production server. I guess I must have had IIS set to forbid requests without an agent specified. – secretwep Nov 16 '15 at 02:37
  • ditto Spotify ATOM feeds – planetClaire Mar 14 '17 at 01:01
  • I also arrived here after getting a 403 from the GitHub API. Later I found this documentation where GitHub states that UserAgent is required: https://developer.github.com/v3/#user-agent-required – Bill Menees Jul 17 '20 at 17:12
24

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.

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.

x0n
  • 51,312
  • 7
  • 89
  • 111
  • Sorry for the delay, I was just testing. Your first suggestion has solved the problem. Thank you very much! –  May 24 '13 at 13:48
3

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.

Lotok
  • 4,517
  • 1
  • 34
  • 44
  • Does Admin account have permission on web server receiving the request? Keeping in mind MyLocalPC\Administrator and server\Administrator are not the same account – Lotok May 24 '13 at 12:35
2

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

Vishnu Prasanth
  • 149
  • 1
  • 5
1

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
comiventor
  • 3,922
  • 5
  • 50
  • 77
Abul
  • 11
  • 1
  • In my case I had to add the following values and that made it to work: webReq.UseDefaultCredentials = true; webReq.UserAgent = "My API Agent"; webReq.Referer = ; – msola Apr 27 '21 at 18:51
0
    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();
    }
Sanesh
  • 1
  • 5
    don't put an answer without an explanation. Please explain what you're recommending. This is a large block of code that may answer the question, but should be paired with some detail. – Cayce K May 01 '15 at 19:27
0

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.

W. Boldt
  • 11
  • 6
0

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.

Roger Perkins
  • 376
  • 2
  • 9
0

Setting:

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

and adding cookies than worked for me

John
  • 29,788
  • 18
  • 89
  • 130
anju
  • 1
0

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
}
Bilal Ahmed
  • 1,043
  • 4
  • 17
  • 32
0

Just had this error. The problem was that the client computer had a wrong date/time in Windows.

0

I changed my project location and got this error. I used to remove this project from IIS (IIS contains old project reference), restart it, open my project in VS as admin and run it from VS. This resolved my issue.

Hope it will works for someone.

UC57
  • 359
  • 4
  • 16