How to enable CORS in ASP.NET Core WebAPI

By FoxLearn 12/5/2024 12:29:44 PM   53
To enable Cross-Origin Resource Sharing (CORS) in an ASP.NET Core Web API project, follow these steps.

When you're working with an ASP.NET Core Web API, enabling Cross-Origin Resource Sharing (CORS) is essential for allowing your API to accept requests from different origins (such as different domains or ports).

In this article, we'll walk through a straightforward way to implement CORS, focusing on a simple case where your API accepts requests from one specific domain.

CORS Implementation in ASP NET Core Web API

If you haven't already added CORS support to your project, the first step is to install the necessary NuGet package. In ASP.NET Core, CORS support is provided by the Microsoft.AspNetCore.Cors package.

To install it, run the following command in your project directory:

Install-Package Microsoft.AspNetCore.Cors

This package is essential to enable CORS functionality in your API.

Next, you'll need to register the CORS services in your Startup.cs file. In the ConfigureServices method, add the AddCors method before any calls to add MVC or other services. This ensures that CORS is set up correctly before your application starts handling requests.

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(); // Register the CORS services
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

By calling AddCors, you enable your application to use CORS. At this point, no specific CORS policy has been defined yet, but the necessary services are in place.

Now, you'll define the actual CORS policy in the Configure method of your Startup.cs file.

This is where you specify which origins (domains) are allowed to make requests to your API. For a simple scenario where you only want to allow requests from one specific domain (e.g., http://example.com), you can configure CORS like this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    // Make sure you call this before app.UseMvc()
    app.UseCors(options => options.WithOrigins("http://example.com").AllowAnyMethod());
    app.UseMvc();
}

It's critical that the UseCors method is called before any other middleware that processes requests (like UseMvc() in this case). Otherwise, the CORS policy might not be applied correctly.

  • WithOrigins("http://example.com"): This allows requests from http://example.com only. You can replace this URL with your own allowed domain.
  • AllowAnyMethod(): This allows any HTTP method (GET, POST, PUT, DELETE, etc.). If you want to restrict the methods, you can replace AllowAnyMethod() with a more specific method like WithMethods("GET", "POST").

If you want to allow different origins for different routes or actions, you can define a named CORS policy in the ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("MyPolicy", builder =>
            builder.WithOrigins("http://example.com", "http://anotherdomain.com")
                   .AllowAnyMethod()
                   .AllowAnyHeader());
    });

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

Then, apply it in the Configure method:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseCors("MyPolicy"); // Apply the "MyPolicy" policy

    app.UseMvc();
}

By following this approach, you can enable CORS in a straightforward and efficient manner, ensuring that your API can be accessed by trusted domains without overcomplicating the configuration.