Allow CORS Requests From Any Origin In .NET Core

In this article, we will learn how to allow CORS requests from any origin in .NET Core.

When we use .NET Core API on a different domain it will returns an error as given below. The error says that the browser is blocking the request as it usually allows a request in the same origin for security reasons.

To fix the issue to allow CORS requests from any origin in .NET Core, open the Startup.cs file, and just follow the steps given below.

Place the below code under the Configure() method to register and configure the CORS policy.

Then, under the ConfigureServices() method, use the below code to apply the CORS policy.

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

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

        // 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.UseRouting();

            app.UseCors(x => x
                .AllowAnyMethod()
                .AllowAnyHeader()
                .SetIsOriginAllowed(origin => true));

            app.UseAuthorization();

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

Please give your valuable feedback and if you have any questions or issues about this article, please let me know.

Also, check Drag & Drop Image Upload In Angular 10 With .NET Core

Submit a Comment

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

Footer Logo

Subscribe

Select Categories