How to resolve CORS issue in C# ASP.NET WebAPI?


Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own.

For example, let us consider an application which is having its front end (UI) and back end (Service). Say the front-end is served from https://demodomain-ui.com and the backend is served from from https://demodomain-service.com/api. If an end user tries to access the application, for security reasons the browsers restrict cross-origin HTTP requests initiated from the UI.

So to overcome this, the CORS standard is needed because it allows servers to specify not just who can access its assets, but also how the assets can be accessed. Cross-origin requests are made using the standard HTTP request methods. Most servers will allow GET requests, meaning they will allow resources from external origins (say, a web page) to read their assets. HTTP requests methods like PATCH, PUT, or DELETE. The following are the HTTP headers added by the CORS standard −

  • Access-Control-Allow-Origin

  • Access-Control-Allow-Credentials

  • Access-Control-Allow-Headers

  • Access-Control-Allow-Methods

  • Access-Control-Expose-Headers

  • Access-Control-Max-Age

  • Access-Control-Request-Headers

  • Access-Control-Request-Method

  • Origin

Enabling CORS at global level

The first is to install the Microsoft.AspNet.WebApi.Cors from the Nuget package manager.

Then Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method −

Enabling CORS at Controller and Action level

We can also enable CORS at the controller or action method level like below.

Example

using System.Web.Http;
using System.Web.Http.Cors;
namespace DemoWebApplication.Controllers{
   [EnableCors("*", "*", "*")] //Controller level
   public class DemoController : ApiController{
      [EnableCors("*", "*", "*")] //Action level
      public IHttpActionResult Get(int id){
         return Ok();
      }
   }
}

Similarly, we can disable the cors by using [DisableCors] attribute.

Updated on: 19-Aug-2020

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements