How to use OWIN for CORS

XMLHttpRequest cannot load https://localhost:44333/api/Location?cityName=pune. No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘https://localhost:44373’ is therefore not allowed access.

This was the error I got while accessing my WebAPI from my client app. This actually means that right now my Web API does not support CORS. So if you watch the network traffic in Chrome developer tool, you will see that browser does send GET request and the request succeeds but the AJAX call return an error. It means same origin policy does not prevent the browser from sending the request but prevent the application from seeing the response.

cors_api

ENABLING CORS in WEB API

To enable CORS we need to install few nuget in WEB API app. Below are the required nuget to enable CORS:

  1. Microsoft.Owin;
  2. Microsoft.Owin.Cors

Now add a class file Startup.cs in App_Start folder. Add following code in it.

After doing all this I thought my task is over and I run my code to make ajax call to the service and when I clicked the button to make ajax call to the service it didn’t worked and I got above error in console of developer tool.

I was confused why I am getting this error as I have followed the required procedure for implementing CORS.

Later on I found out that I was missing some entries in web.config which are required for CORS to work properly.

After these entries in web.config inside <system.WebServer> tag my code starting woking perfectly.

Hope this helps you all.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s