Many times while calling a Web-Api through JQuery ajax calls, we face issues like Access-Control-Allow-Origin. We encounter this error as the resource or Web-Api that we are trying to access is hosted in a different domain then the client which is trying to consume it. Security is the prime reason behind forbidding this sharing of resources across domains as the interaction that occurs through Ajax verbs i.e. Get, Post , Put , Delete also introduce risks of Cross Side Scripting. CORS – Cross Origin Resource Sharing is the mechanism through which we can control the sharing of resources across domains. If we want a Web-Api to be accessed by clients at different domains we can enable the CORS for the Web-API. Steps to enable CORS : In the Web-Api solution go to the References and select Manage NuGet Packages. Search for the CORS and you will find a package named as Microsoft ASP-NET Cross-Origin Support. Install the package.
Try to build the solution and run it. You may or may not encounter any issue related to assembly version when you try to browse the API. If you encounter an issue like below.
This error is encountered because there is a mismatch in the assembly after installing the CORS. Just add the below Assembly binding in the Web Config.
Notice that 184.108.40.206 is the version that we have used for System.Web.Http and it is the same version of the CORS that we have installed. So this steps completes the installation process. You may also encounter a problem as below.
To resolve this error we need to uninstall the Mvc.FixedDisplayModes from Nuget package manager console using below command.
After installing the CORS library we have to make few code changes. In MVC WebAPI solution for the routes we have RouteConfig and WebRouteConfig files under App_Start Folder. As we are dealing with WebApi so WebRouteConfig is the one where we need to add a line to enable cors. Just add the below line of code at the starting of register method.
Now in the API we may have many controllers and may be as per requirement you may want to expose some specific controllers to the outer domain , so whichever controller need to be exposed we need to decorate it with following.
You can see three properties in the EnableCors namely origins, headers and methods. If you want to specify a specific website which will be able to communicate with this API controller from another domain through Ajax request then you may write that specific website as origins : “http://localhost:49402” . But we have provided * to allow all the websites so that the API controller methods can be accessed by any of the website. Similarly we can filter the methods and headers. This is how CORS can be enabled in the MVC Web-API . Hope this helps.