As we know, cross-site HTTP requests from scripts are restricted due to security reasons. Basically, if our web application runs on a domain (myapp.com), and we try to make a web service call via AJAX to a different domain (myservice.com), we get a cross domain error (not allowed). In the world of Web API and web services in general, we have the need to support cross domain requests because we may be building a service layer with the purpose to be consumed by multiple web applications with different domains.
This need has been identified by the WebApps Working Group which is part of the W3C, and the Cross-Origin Resource Sharing (CORS) recommendation was made. This allows us to enable web services to support cross-site HTTP requests.
A way to address this for Web API is to create a delegating handler that can authorize the request from different domains. Lucky for us, there is already a NuGet package that can be installed on our project. To install it, we can just enter the following on the Package Manager Console:
PM> Install-Package Thinktecture.IdentityModel
Once this handler is installed, we just need to register the CORS support in our global.asax Application_Start event handler. This can be done with the following snippet:
using Thinktecture.IdentityModel.Http.Cors.WebApi;
protected void Application_Start()
{
...
CrossOriginResourceSharing(GlobalConfiguration.Configuration);
}
void CrossOriginResourceSharing(HttpConfiguration httpConfig)
{
string origin = "CrossDomainUrl";
if (!String.IsNullOrWhiteSpace(origin))
{
var corsConfig = new WebApiCorsConfiguration();
corsConfig.RegisterGlobal(httpConfig);
corsConfig.ForOrigins(origin).AllowAll();
}
}
In this code, we are just setting one single domain in the ForOrigins method, but there is support for multiple domains. We are also allowing cross domain access for all the resources, but if we need to allow access to only one resource/controller, we can use this method instead:
corsConfig.ForResources("Controller1").ForOrigins(origin).AllowAll();
If we need to control the methods (GET/POST), we can also use the following:
corsConfig.ForOrigins(origin).AllowMethods("GET").AllowAll();
One more thing to note is that this library also supports ASP.NET MVC and Web Forms application. For those web applications, the implementation is done with an HTTP module, so in addition to registering the CORS support, we also need to add the Module setting in the web.config file.
I hope this article is able to give you some understanding on how to address Cross-Domain access for Web API services. There is more information to learn about this library, so I advise to read more about it and learn all the capabilities that are available.