Sometimes it is necessary to overcome browser restrictions(making AJAX requests to another domain). CORS (Cross Origin Resource Sharing) allows us to relax the same-origin policy.
The name AJAX is used also for XMLHttpRequest in this blog as AJAX uses XMLHttpRequest. This blog is applicable only for web api 2 applications based on .Net Framework 4.x
It is a good thing that browser prevents a web page from making AJAX request to another domain. However, sometimes, we need to relax this policy to test some apps on localhost or if the app is an API endpoint and is being consumed by cross-domain apps.
I encountered this same-origin policy when I was testing two related apps on localhost. Because the two apps running of localhost had a different port number, they are considered as cross-domain by the browser, hence, they prevent AJAX request. It was very frustrating as I was unable to make an AJAX call to another app running on localhost.
This restriction can be overcome using any of the two approaches:
According to MDN, CORS allows AJAX request to be made by a cross-origin app. It is an HTTP-header based mechanism to indicate any other origins.
The good thing is that asp.net web API 2.x applications can use a Nuget package to enable CORS.
It can be installed either by using 'Manage Nuget Packages' option or just by typing following command on Package-Manager
Install-Package Microsoft.AspNet.WebApi.Cors
We need to tell App_Start/WebApiConfig.cs to enable CORS by
public static void Register(HttpConfiguration config)
{
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Now, we need to configure controller to accept cross-origin request by using EnableCors attribute.
using System.Web.Http.Cors;
namespace MyWebAPI.Controllers
{
[EnableCors(origins: "https://localhost:44301/client1", headers: "*", methods: "*")]
public class MyApiController : ApiController
{
// Controller methods removed for brevity...
}
}
Remember NOT to use Forward slash (/) at the end of origin url. F.ex, https://localhost:44301/client1/
[EnableCors(origins: "https://localhost:44301/client1, https://localhost:44301/client2", headers: "*", methods: "*")]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public static void Register(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("https://localhost:44301/client", "*", "*");
config.EnableCors(cors);
// other code removed for brevity...
}
using System.Web.Http.Cors;
namespace MyWebAPI.Controllers
{
[EnableCors(origins: "https://localhost:44301/client1", headers: "*", methods: "get")]
public class MyApiController : ApiController
{
// Controller methods removed for brevity...
}
}