Blocked cross-origin request

Asked

Viewed 2,885 times

5

Hello, I am trying to load a page from another application into a div of my application using the jQuery load but my application is not loading the page and shows the following error message:

Blocked cross-origin request: Same Origin Policy (Same Origin Policy) prevents reading of the remote resource

(Reason: CORS header 'Access-Control-Allow-Origin' is not present).

My application view code:

<div id="pagina">
</div>
@section scripts
{
    <script type="text/javascript">
        $("#pagina").load("http://localhost:4576/");
    </script>
}

Does anyone know how I could solve this?

Thank you.

  • 1

    See if this question helps : http://answall.com/questions/3183/requisi%C3%A7%C3%A3o-ajax-cross-Domain-with-javascript-neat-without-Apis

  • Then you answer your question like you did in iis.

2 answers

4

The most elegant solution I know implements a Attribute which allows accepting the request depending on the Action or of Controller called. I do not recommend registering the Attribute globally.

1. Create a new Attribute

public class AllowCrossSiteAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
        base.OnActionExecuting(filterContext);
    }
}

2. Register the Action with the Attribute

[AllowCrossSite]
public ActionResult Index()
{
    return View();
}

3. Install the CorsProxy.AspNet for retroactive compatibility with the IE

Install-Package CorsProxy.AspNet

3.1. Route configuration with the CorsProxy

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        // Coloque antes da rota padrão.
        routes.EnableCorsProxy();

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

    }
}

3.2. Configuration of Bundles with the CorsProxy

public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-{version}.js",
                    // Coloque os demais scripts relativos ao jQuery aqui
                    "~/Scripts/jquery-corsproxy-{version}.js"));
        ...
    }
}

3.3. Implement a Handler for CORS requests

public class CorsProxyHttpHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        var url = context.Request.Headers["X-CorsProxy-Url"];
        if (url == null)
        {
            context.Response.StatusCode = 501;
            context.Response.StatusDescription =
                "X-CorsProxy-Url was not specified. The corsproxy should only be invoked from the proxy JavaScript.";
            context.Response.End();
            return;
        }

        try
        {
            var request = WebRequest.CreateHttp(url);
            context.Request.CopyHeadersTo(request);
            request.Method = context.Request.HttpMethod;
            request.ContentType = context.Request.ContentType;
            request.UserAgent = context.Request.UserAgent;

            if (context.Request.AcceptTypes != null)
            request.Accept = string.Join(";", context.Request.AcceptTypes);

            if (context.Request.UrlReferrer != null)
                request.Referer = context.Request.UrlReferrer.ToString();

            if (!context.Request.HttpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase))
                context.Request.InputStream.CopyTo(request.GetRequestStream());

            var response = (HttpWebResponse)request.GetResponse();
            response.CopyHeadersTo(context.Response);
            context.Response.ContentType = response.ContentType;
            context.Response.StatusCode =(int) response.StatusCode;
            context.Response.StatusDescription = response.StatusDescription;

            var stream = response.GetResponseStream();
            if (stream != null && response.ContentLength > 0)
            {
                stream.CopyTo(context.Response.OutputStream);
                stream.Flush();
            }
        }
        catch (WebException exception)
        {
            context.Response.AddHeader("X-CorsProxy-InternalFailure",  "false");

            var response = exception.Response as HttpWebResponse;
            if (response != null)
            {
                context.Response.StatusCode = (int)response.StatusCode;
                context.Response.StatusDescription = response.StatusDescription;
                response.CopyHeadersTo(context.Response);
                var stream = response.GetResponseStream();
                if (stream != null)
                    stream.CopyTo(context.Response.OutputStream);

                return;
            }

            context.Response.StatusCode = 501;
            context.Response.StatusDescription = exception.Status.ToString();
            var msg = Encoding.ASCII.GetBytes(exception.Message);
            context.Response.OutputStream.Write(msg, 0, msg.Length);
            context.Response.Close();

        }
        catch (Exception exception)
        {
            context.Response.StatusCode = 501;
            context.Response.StatusDescription = "Failed to call proxied url.";
            context.Response.AddHeader("X-CorsProxy-InternalFailure", "true");
            var msg = Encoding.ASCII.GetBytes(exception.Message);
            context.Response.OutputStream.Write(msg, 0, msg.Length);
            context.Response.Close();

        }
    }

    public bool IsReusable { get { return true; }}
}

3.4. Setting the Ajax call

Before your .load, configure jQuery with the following:

$.ajaxPrefilter(function (options, originalOptions, jqXhr) {
    if (!window.CorsProxyUrl) {
        window.CorsProxyUrl = '/corsproxy/';
    }
    // only proxy those requests
    // that are marked as crossDomain requests.
    if (!options.crossDomain) {
        return;
    }

    if (getIeVersion() && getIeVersion() < 10) {
        var url = options.url;
        options.beforeSend = function (request) {
            request.setRequestHeader("X-CorsProxy-Url", url);
        };
        options.url = window.CorsProxyUrl;
        options.crossDomain = false;
    }
});

The original explanation is here.

2

Friend already solved this problem just by adding the tag:

<add name="Access-Control-Allow-Origin" value="*" />

on my web config..

follows the full web.config:

<location path="Sample.txt">
<system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
    </customHeaders>
  </httpProtocol>
</system.webServer>

  • 2

    The only however of this solution is that releases requests cross-origin for all the Actions of all the Controllers. I don’t think it’s safe to wear this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.