DEV Community

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Posted on

How to Solve CORS Origin Issue in Asp.Net Core Web API

To solve the CORS (Cross-Origin Resource Sharing) issue in ASP.NET Core Web API, you can follow these steps:

Step 1: Install the required NuGet packages

Make sure you have the following NuGet packages installed in your ASP.NET Core Web API project:

Microsoft.AspNetCore.Cors: This package provides CORS middleware to enable Cross-Origin Resource Sharing.

You can install the package using the Package Manager Console or NuGet Package Manager in Visual Studio.

Step 2: Configure CORS in your ASP.NET Core Web API project

In the Startup.cs file, locate the ConfigureServices method and add the following code to enable CORS:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("CorsPolicy", builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        });
    });

    // Other service configurations
}

Enter fullscreen mode Exit fullscreen mode

In the code above, AddCors adds CORS services to the dependency injection container, and AddPolicy defines a CORS policy named "CorsPolicy". The policy is configured to allow any origin, method, and header. You can modify these settings to meet your specific requirements.

Step 3: Enable CORS in the request pipeline

In the Configure method of the Startup.cs file, add the following code to enable CORS in the request pipeline:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // Other configuration settings

    app.UseCors("CorsPolicy");

    // Other middleware configurations
}

Enter fullscreen mode Exit fullscreen mode

The UseCors method configures the CORS middleware to use the policy named "CorsPolicy" defined earlier.

Step 4: Testing CORS

Now you should be able to make cross-origin requests to your ASP.NET Core Web API. The API should include the appropriate CORS headers in the response, allowing requests from different origins.

It's important to note that allowing any origin (AllowAnyOrigin()) may not be suitable for production environments. You should consider limiting the origins, methods, and headers based on your specific requirements.

By Following these steps you can solve the CORS Origin Issue

Top comments (0)