Search This Blog

Thursday, December 27, 2018

Web API : How to enable CORS in web api (.net core)?

The browsers don't allow the cross-origin-resource-sharing(CORS) for the security reasons. But nowadays almost websites use the APIs hosted on different origin. To overcome from this problem we need to do the below setting at API side to allow the CORS.
  1. Check if the package "Microsoft.AspnetCore.Cors" is installed into the web api project otherwise install it either from nuget package manager or from below command line in VS Code/ Command --

    dotnet add package Microsoft.AspnetCore.Cors

  2. Open Startup.cs file and do the below setting

    public void ConfigureServices(IServiceCollection services)
    {
       services.AddCors();
      services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
      ...
      app.UseCors(options=> options.WithOrigins("http://www.domainexample.com").AllowAnyMethod() );

      //If you are in development phase or you don't who ever is using you API then the below setting is recommended
      //app.UseCors(options=> options.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());

      ...
    }
    In above code "http://www.domainexample.com" could be any valid domain for which it needs to enable CORS .

No comments:

Post a Comment