Ehsan Ghanbari

Experience, DotNet, Solutions

Enabling the CORS in Asp.net Core

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();

        }

 

About Me

Ehsan Ghanbari

Hi! my name is Ehsan. I'm a developer, passionate technologist, and fan of clean code. I'm interested in enterprise and large-scale applications architecture and design patterns and I'm spending a lot of my time on architecture subject. Since 2008, I've been as a developer for companies and organizations and I've been focusing on Microsoft ecosystem all the time. During the&nb Read More

Post Tags
Pending Blog Posts
Strategic design
Factory Pattern
time out pattern in ajax
Selectors in Jquery
using Log4net in asp.net MVC4
How to use PagedList In asp.net MVC
Redis as a cache server
Domain driven design VS model driven architecture
What's the DDD-lite?
Multiple submit buttons in asp.net MVC
comments powered by Disqus