System net webexception удаленный сервер возвратил ошибку 403 запрещено

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:PathMainWindow.xaml.cs:line 3759
   at XApp.MainWindow.GetLinks() in J:PathMainWindow.xaml.cs:line 2454
   at XApp.MainWindow..ctor() in J:PathMainWindow.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:PathMainWindow.xaml.cs:line 3759
   at XApp.MainWindow.GetLinks() in J:PathMainWindow.xaml.cs:line 2454
   at XApp.MainWindow..ctor() in J:PathMainWindow.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


 }

I’m using the Google API on my website. It works
fine from my localhost, but on the live server I get the following
error:

System.Net.WebException: The remote server returned an error: (403)
Forbidden.
at System.Net.HttpWebRequest.GetResponse()
at GoogleUrlShortnerApi.Shorten(String url)

I’m using the code found here:
http://www.thecyberwizard.com/index.php/5/google-analytics-api-in-c-part-1/

And from debugging, I see that the error occurs on the

HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();

command.

Does anyone know what could be causing the error (again, the error
happens only on the server. When I run this code locally on my
computer, it runs fine and retrieves a short url).

I have to turn off billing still I get the following
error:

System.Net.WebException: The remote server returned an error: (403)  

How can I resolve this?

User-1078128378 posted

Hi All,

I want to fetch my gmail friends list

I am using the following code

friends.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Friends.aspx.cs" Inherits="Friends" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        body
        {
            font-family: Arial;
            font-size: 10pt;
        }
        table
        {
            border: 1px solid #ccc;
        }
        table th
        {
            background-color: #F7F7F7;
            color: #333;
            font-weight: bold;
        }
        table th, table td
        {
            padding: 5px;
            border-color: #ccc;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
<asp:Button ID="btnLogin" Text="Login" runat="server" OnClick="Login" />
<asp:Panel ID="pnlProfile" runat="server" Visible="false">
<hr />
<asp:GridView ID="gvContacts" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:TemplateField HeaderText="Photo" HeaderStyle-Width="60">
            <ItemTemplate>
                <asp:Image ID="Image1" ImageUrl='<%# Eval("PhotoUrl") %>' runat="server" onerror="this.src='default.png';" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="Name" HeaderText="Name" HeaderStyle-Width="100" />
        <asp:BoundField DataField="Email" HeaderText="Email Address" HeaderStyle-Width="100" />
    </Columns>
</asp:GridView>
</asp:Panel>
    </div>
    </form>
</body>
</html>

friends.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using ASPSnippets.GoogleAPI;
using System.Web.Script.Serialization;

public partial class Friends : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        GoogleConnect.ClientId = "640644024552-5liq6s2s1o1ekdbmhn2ufo9d0o4mppe4.apps.googleusercontent.com";
        GoogleConnect.ClientSecret = "6IwoiG7TqMVf7NqjliER66la";
        GoogleConnect.RedirectUri = "http://localhost:60767/Friends.aspx";
        GoogleConnect.API = EnumAPI.Contacts;
        if (!string.IsNullOrEmpty(Request.QueryString["code"]))
        {
            string code = Request.QueryString["code"];
            string json = GoogleConnect.Fetch("me", code, 10);
            GoogleContacts profile = new JavaScriptSerializer().Deserialize<GoogleContacts>(json);
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Name", typeof(string)),
                        new DataColumn("Email", typeof(string)),
                        new DataColumn("PhotoUrl",typeof(string)) });

            foreach (Contact contact in profile.Feed.Entry)
            {
                string name = contact.Title.T;
                string email = contact.GdEmail.Find(p => p.Primary).Address;
                Link photo = contact.Link.Find(p => p.Rel.EndsWith("#photo"));
                string photoUrl = GoogleConnect.GetPhotoUrl(photo != null ? photo.Href : "~/default.png");
                dt.Rows.Add(name, email, photoUrl);
                gvContacts.DataSource = dt;
                gvContacts.DataBind();
            }
            pnlProfile.Visible = true;
            btnLogin.Enabled = false;
        }
        if (Request.QueryString["error"] == "access_denied")
        {
            ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "alert('Access denied.')", true);
        }
    }

    protected void Login(object sender, EventArgs e)
    {
        GoogleConnect.Authorize(Server.UrlEncode("https://www.google.com/m8/feeds/"));
    }


    public class GoogleContacts
    {
        public Feed Feed { get; set; }
    }

    public class Feed
    {
        public GoogleTitle Title { get; set; }
        public List<Contact> Entry { get; set; }
    }

    public class GoogleTitle
    {
        public string T { get; set; }
    }

    public class Contact
    {
        public GoogleTitle Title { get; set; }
        public List<Email> GdEmail { get; set; }
        public List<Link> Link { get; set; }
    }
    public class Email
    {
        public string Address { get; set; }
        public bool Primary { get; set; }
    }

    public class Link
    {
        public string Rel { get; set; }
        public string Type { get; set; }
        public string Href { get; set; }
    }
}

i am getting following error

Server Error in ‘/’ Application.


The remote server returned an error: (403) Forbidden.

Description: An
unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Net.WebException: The remote server returned an error: (403) Forbidden.

Source Error:

Line 21:         {
Line 22:             string code = Request.QueryString["code"];
Line 23:             string json = GoogleConnect.Fetch("me", code, 10);
Line 24:             GoogleContacts profile = new JavaScriptSerializer().Deserialize<GoogleContacts>(json);
Line 25:             DataTable dt = new DataTable();


Source File: d:Asp WebsitesGoogleLoginFriends.aspx.cs    Line: 23 

Stack Trace:

[WebException: The remote server returned an error: (403) Forbidden.]
   System.Net.HttpWebRequest.GetResponse() +6518932
   ASPSnippets.GoogleAPI.GoogleConnect.?3?(String ?11?) +128
   ASPSnippets.GoogleAPI.GoogleConnect.Fetch(String ?6?, String ?7?, Int32 ?8?) +1048
   Friends.Page_Load(Object sender, EventArgs e) in d:Asp WebsitesGoogleLoginFriends.aspx.cs:23
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
   System.Web.UI.Control.OnLoad(EventArgs e) +92
   System.Web.UI.Control.LoadRecursive() +54
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34212

whats wrong in my code?

or is there any other example to get my gmail friends list?

Thanks,

Murali.

I have created a SharePoint 2016 app (add-in) using visual studio 2019. Everything is what the boiler template provides in Visual studio, so no changes in the code.

I created a self-signed certificate, added it to Central admin, generated the Issuer Id and added that in the web.config.

When I deploy the app, I get the 403 error.

I am administrator in the dev machine.

The remote server returned an error: (403) Forbidden.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Net.WebException: The remote server returned an error: (403) Forbidden.

Source Error:

Line 32:                     clientContext.AuthenticationMode = ClientAuthenticationMode.Default;
Line 33: 
Line 34:                     clientContext.ExecuteQuery();
Line 35: 
Line 36:                     ViewBag.UserName = spUser.Title;

Source File: C:Usersdev1sourcereposSharePointAddIn6SharePointAddIn6WebControllersHomeController.cs    Line: 34

Stack Trace:

[WebException: The remote server returned an error: (403) Forbidden.]
   System.Net.HttpWebRequest.GetResponse() +1399
   Microsoft.SharePoint.Client.SPWebRequestExecutor.Execute() +37
   Microsoft.SharePoint.Client.ClientRequest.ExecuteQueryToServer(ChunkStringBuilder sb) +615
   Microsoft.SharePoint.Client.ClientRequest.ExecuteQuery() +47
   Microsoft.SharePoint.Client.ClientRuntimeContext.ExecuteQuery() +89
   Microsoft.SharePoint.Client.ClientContext.ExecuteQuery() +495

Fiddler is giving me this error:

App settings are:

  <appSettings>
    <add key=»ClientSigningCertificatePath» value=»C:CertsDemoCert.pfx» />
    <add key=»ClientSigningCertificatePassword» value=»password» />
    <add key=»IssuerId» value=»f064f558-9df6-4003-9f8f-45734d4ae7b1″ />
  </appSettings>

What am I doing wrong?

Я написал приложение, которое отлично работало в течение нескольких месяцев, в последние несколько дней я получал ошибку ниже только в установленной версии.

Если я запускаю исходный код в VS, все работает нормально. Кроме того, файл .exe в папках bin работает нормально. Это только установленная версия, которая генерирует ошибку, если я перекомпилирую и переустановить, я получаю ту же ошибку.

Я немного озадачен тем, что вызывает это, и надеялся на несколько указателей. Кажется, что ответ WebRequest через IE не возвращается, но я в тупике, почему он отлично работает в 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:PathMainWindow.xaml.cs:line 3759
   at XApp.MainWindow.GetLinks() in J:PathMainWindow.xaml.cs:line 2454
   at XApp.MainWindow..ctor() in J:PathMainWindow.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:PathMainWindow.xaml.cs:line 3759
   at XApp.MainWindow.GetLinks() in J:PathMainWindow.xaml.cs:line 2454
   at XApp.MainWindow..ctor() in J:PathMainWindow.xaml.cs:line 124

EDIT:

Это установлено как отдельное приложение. Когда я запускаю Администратор, я открыл папку программы и запускаю 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


 }

Понравилась статья? Поделить с друзьями:
  • System net webexception удаленный сервер возвратил ошибку 401 несанкционированный
  • System net http httprequestexception произошла ошибка при отправке запроса
  • System launcher ошибка загрузки xiaomi
  • System kernel power 41 причины ошибки
  • System is not defined ошибка