Cross-Origin Resource Sharing Example with ASP.NET
Table of Contents
Introduction
This is a simple example of how to achieve cross-domain access in ASP.NET. The following example is the simplest approach, which just makes it work by modifying web.config.
Let's assume you have the following two sites. client-site.com is trying to
access server-site.com's Ajax API, /api/getMyData.
-
client-site.com
-
server-site.com
- contains
/api/getMyData
- contains
Server-Side Configuration
What you have to do at server-site.com is the following — you let
your server return the Access-Control-Allow-Origin header in the HTTP
response.
Client-Side Ajax Call
On client-site.com you can just call as follows, assuming your API is at server-site.com/api/getMyData:
$.ajax({ url: "http://server-site.com/api/getMyData" }).then(function () {
console.info("done with call server-site.com's api");
});
Further Reading
For more detailed information about how to enable CORS for a specific HTTP method, a specific site, or other useful libraries, see:
Enabling Cross-Origin Requests in ASP.NET Web API 2
Conclusion
By adding the Access-Control-Allow-Origin header in your web.config, you can quickly enable cross-domain access in ASP.NET. For more fine-grained control, consider using the ASP.NET Web API 2 CORS library.