In this article, we are going to learn how to resolve CORS errors in .Net MVC.
What is CORS?
CORS stands for Cross-Origin Resource Sharing.
It is a mechanism that allows us to restricted resources on a web page that is requested from another domain that is outside the domain from where the first resource was served.
CORS error occurs while calling API from angular.
You can see the above error in the console log, this error can solve while doing some settings in .Net Application settings.
First, install the below package.
Install-Package Microsoft.AspNet.WebApi.Cors
The Open WebApiConfig file and add the below line in it.
public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.EnableCors(); config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } }
Then after add the install package to the controller.
using System.Collections.Generic; using System.Web.Http; using System.Web.Http.Cors; namespace CorsDemo.Controllers { [EnableCors(origins: "*", headers: "*", methods: "*")] public class TechnologyController : ApiController { // GET: api/Technology public IEnumerable<string> Get() { return new string[] { "C#", "ASP.NET", "MVC", ".NetCore", "C++" }; } } }
Summary:
Initializes a new instance of the System.Web.Http.Cors.EnableCorsAttribute class.
Parameters:
origins:
Comma-separated list of origins that are allowed to access the resource. Use “*” to allow all.
headers:
Comma-separated list of headers that are supported by the resource. Use “*” to allow all. Use a null or empty string to allow none.
methods:
Comma-separated list of methods that are supported by the resource. Use “*” to allow all. Use a null or empty string to allow none.
You can also use a particular URL in origins let’s understand with the below example.
using System.Collections.Generic; using System.Web.Http; using System.Web.Http.Cors; namespace CorsDemo.Controllers { [EnableCors(origins: "http://localhost:50164/", headers: "*", methods: "get,post")] public class TechnologyController : ApiController { // GET: api/Technology public IEnumerable<string> Get() { return new string[] { "C#", "ASP.NET", "MVC", ".NetCore", "C++" }; } } }
Also check, Custom Authorization In .NET Core 5.0