When you are trying to do an http post from your Jquery, Angular or any client side script language to an web API that has a different domain name as yours, you will be getting error on the web browser that says:
No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘null’ is therefore not allowed access.
This is happening because the website and web API has a different domain names. solving this issue can be done using the following steps:
- On the wbe API project, Right click References and select “Manage Nuget”
- Search for “Cors” and install “Microsoft.AspNet.WebApi.Cors” , this will install a new dll to your project; System.Web.Http.Cors
- go to App_Start/WebApiConfig.cs file
- Add using statement to include System.Web.Http.Cors
- On Register method, add the following 2 lines
var cors = new EnableCorsAttribute("*", "*", "*"); config.EnableCors(cors);
the EnableCorsAttribute has the following 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 null or empty string to allow none.
Methods: Comma-separated list of methods that are supported by the resource. Use “*” to allow all. Use null or empty string to allow none.