Blog

Filter posts by Category Or Tag of the Blog section!

Enabling the CORS in Asp.net Core

Tuesday, 23 October 2018

As I'm talking with Asp.net core these days, so I'm supposed to be eager about that! In asp.net core, in order to enable the CORS, you should refer to application startup and ConfigureServices and add the following configuration:

 

 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.Configure<CookiePolicyOptions>(options =>

            {

                // This lambda determines whether user consent for non-essential cookies is needed for a given request.

                options.CheckConsentNeeded = context => true;

                options.MinimumSameSitePolicy = SameSiteMode.None;

            });


            services.AddCors(o => o.AddPolicy("MyPolicyName", builder =>

            {

                builder.AllowAnyOrigin()

                       .AllowAnyMethod()

                       .AllowAnyHeader();

            }));

 
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();


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

        }

 

 Now for applying the above policy in your controller or action, you just need to use it via attribute:

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using Microsoft.AspNetCore.Cors;

using Microsoft.AspNetCore.Mvc;

 

namespace WebApplication3.Controllers

{

    [EnableCors(policyName: "MyPolicyName")]

    public class DefaultController : Controller

    {

        [EnableCors(policyName: "MyPolicyName")]

        public IActionResult Index()

        {

            return View();

        }

    }

}

 

And, in order to apply for every request, you can config it like below in startup class: 

 


 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)

        {

            app.UseCors("MyPolicyName");

 

            if (env.IsDevelopment())

            {

                app.UseDeveloperExceptionPage();

            }

            else

            {

                app.UseExceptionHandler("/Error");

                app.UseHsts();

            }

 

            app.UseHttpsRedirection();

            app.UseStaticFiles();

            app.UseCookiePolicy();

 

            app.UseMvc();

        }

 

Category: Software

Tags: Asp.Net

comments powered by Disqus