0
votes

I need to access localhost:5002/api/login through localhost:9000.

I have tried almost all the solutions available online. But I keep getting the following error.

How to present the 'Access-Control-Allow-Origin' on the requested resource.

XMLHttpRequest cannot load localhost:5002/api/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:9000' is therefore not allowed access.

I have tried adding this to the Web.config

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

And In the server side StartUp.cs File I have added the following as well

public void ConfigureServices(IServiceCollection services)

    {  
        services.AddCors(options =>

        {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
        });
        services.AddMvc();
    }

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IUowProvider uowProvider)

    {
        app.UseCors("CorsPolicy");
        app.UseMvc();
    }
2
is this Web API 2?Mithun Pattankar
It would be helpful if you briefly enumerate what you have tried.serpent5
Its not Web API 2. We are using MVC Controllers.Sanjayan

2 Answers

1
votes

Step I: please keep the below code in webconfig and within part:

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

Step II: We have added Application_BeginRequest method in Global.asax class. Generally, this method checks Header's all keys. If it contains with "Origin" and Request HttpMethod is "OPTIONS", then ends all currently buffered output to the client

protected void Application_BeginRequest()
    {
        if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
        {
            Response.Flush();
        }
    }
-1
votes

Normally you should be able to add the CORS configuration to either your WebAPI configuration or web.config.

For the WebAPI configuration you should specify the following:

config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

In the web.config it should look like this:

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

Of course, this allows all origins, so you have to change it to localhost:9000 in your situation. Keep in mind, different ports are different origins, so specifying only localhost isn't sufficient, the port should be added also!