Published on: 06 Oct, 2019

How to enable CORS in ASP.Net Core Web API?

Tumblr Digg Google Plus

Today we are going to learn to create a simple Web API using ASP.Net Core and we want to enable CORS for public users to get access to our Web API.

Before we start you may want to know what is CORS is. CORS stands for Cross-Origin Resource Sharing. By default, CORS policy is standard and applied to web browsers to prevent a Javascript call from a different origin. It means you cannot make a Javascript call to other locations or domain URLs where the origin of the Javascript code is running. The reason CORS is enabled is for security purposes. This to ensure the requests call are not from external servers which can be dangerous.

So when Cors policy is enabled? There is a situation where you want to give external access for public users to access your internal data. You can put some security measurement like the access need to be authenticated first by providing login token, OAuth authentication, etc.

In this example, I am going to give full access to our web API without any restriction. So let's get started by creating a Web API .Net Core project in Visual Studio.

Under the Controllers folder, we are removing the default ValueController.cs file and we add a new controller named MyFirstAPIController

Here is the full code of the MyFirstAPIController class file. As you can see we create one single web api get method that will return a list of fruit names.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace NetCoreWebAPI.Controllers
{
    [Produces("application/json")]
    [Route("api/MyFirstAPI")]
    public class MyFirstAPIController : Controller
    {
        [HttpGet("GetFruits")]
        public async Task<List<string>> GetFruits()
        {
            List<string> fruits = new List<string>();
            fruits.Add("Apple");
            fruits.Add("Banana");
            fruits.Add("Blueberry");
            fruits.Add("Cherry");
            fruits.Add("Mango");
            fruits.Add("Pear");
            fruits.Add("Strawberry");
            return await Task.Run(() =>
            {
                return fruits;
            });
        }
    }
}

If we tried to access the web api browser we will get a return of JSON array file.

To test if CORS policy is enabled or not, we can write a Javascript code in an HTML file and try to use the Web API get method. Here is the sample code.

<!doctype html>
<html>
<body>
	<script>
		fetch("http://core.bytutorial.com/api/MyFirstAPI/GetFruits")
		.then(function(response) {
			response.json().then(data => {
				console.log(data);
			});
		})
		.catch(function(error) {
			console.log(error);
		});
	</script>
</body>
</html>

If you try to run above code by opening the file using any browser. You will receive the following error message. This is the web console screenshot in Chrome browser.

Note: the url of http://core.bytutorial.com is for example only and maybe removed in the future.

How to fix CORS issue in ASP.Net Web API Core?

To fix this problem is quite simple. The first thing we need to do is to install Microsoft.AspNetCore.Cors library and add it to our project. You can install it using Nuget Package Manager in Visual Studio.

https://www.nuget.org/packages/Microsoft.AspNetCore.Cors/

Once the above library has been successfully installed. We need to add two Cors methods in the ConfigureServices and Configure methods under Startup.cs file. The first one will be:

services.AddCors();

Remember this need to be add before the code: services.AddMvc();.

The last method we need to add will be the following code.

 app.UseCors(builder => builder
                        .AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials());

For you easy to review, I will include the whole code in the Startup.cs file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace NetCoreWebAPI
{
    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.AddCors();
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors(builder => builder
                        .AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials());

            app.UseMvc();
        }
    }
}

If we have redeployed the code and try to run the Html file again in the browser. We should receive the following response.

Demo Files

You can download the sample code below.

Download

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.