Asp.net-mvc – Enable CORS In MVC Controller

asp.net-mvc

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

Best Answer

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