How To Fix CORS Error In .Net Core

In this article, we are going to learn how to resolve CORS errors in .Net Core.

What is CORS?

CORS stands for Cross-Origin Resource Sharing.
It is a mechanism that allows us to restricted resources on a web page that is requested from another domain that is outside the domain from where the first resource was served.

CORS error occurs while calling Core API from angular.

You can see the above error in the console log, this error can solve while doing some settings in .Net Core Application settings.

Add the following line Startup.cs class of your application.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace CorsCoreDemo
{
  public class Startup
  {
    public Startup(IConfiguration configuration)
    {
      Configuration = configuration;
    }
    public IConfiguration Configuration { get; }
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
      services.AddControllers();
      services.AddCors(option =>
      {
        option.AddPolicy("AllCors", builder =>
        {
          builder.AllowAnyOrigin();
          builder.AllowAnyHeader();
          builder.AllowAnyMethod();
        });
      });
    }
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      if (env.IsDevelopment())
      {
        app.UseDeveloperExceptionPage();
      }

      app.UseHttpsRedirection();
      app.UseCors("AllCors");
      app.UseRouting();

      app.UseAuthorization();

      app.UseEndpoints(endpoints =>
      {
        endpoints.MapControllers();
      });
    }
  }
}

You can also provide a specific URL to your default policy in Startup.cs class.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace CorsCoreDemo
{
  public class Startup
  {
    public Startup(IConfiguration configuration)
    {
      Configuration = configuration;
    }
    public IConfiguration Configuration { get; }
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
      services.AddControllers();
      services.AddCors(option =>
      {
        option.AddPolicy("AllCors", builder =>
        {
          builder.WithOrigins("https://localhost:44318", "http://localhost:4200");
          builder.AllowAnyHeader();
          builder.AllowAnyMethod();
        });
      });
    }
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      if (env.IsDevelopment())
      {
        app.UseDeveloperExceptionPage();
      }

      app.UseHttpsRedirection();
      app.UseCors("AllCors");
      app.UseRouting();

      app.UseAuthorization();

      app.UseEndpoints(endpoints =>
      {
        endpoints.MapControllers();
      });
    }
  }
}

WithOrigins() allows you to specify particular origins. When listing origins in WithOrigins(), ensure that they don’t have a trailing /, otherwise, the origin will never match and your cross-origin requests will fail.

You can also use WithMethods() instead of AllowAnyMethod().It allows you to specify the method like this WithMethods(“GET”,”POST”).

services.AddCors(option =>
{
    option.AddPolicy("AllCors", builder =>
    {
      builder.WithMethods("GET","POST")
      builder.AllowAnyHeader()
      builder.AllowCredentials()
      builder.WithOrigins("http://localhost:4200");
    });
});

Also check, How To Fix CORS Error In .Net MVC

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories