Enable CORS in Web Api.

    Generally while we are working with Asp.net Web API , we expose the Web Api by self hosting or host it in different domain or different server .

 So CORS (Cross Origin Resource Sharing) comes into play , while we access any Web Api from any other servers or domain which is different from the origin domain .

Let me explain it by an example.

Suppose my application is running on "http://localhost:61375/".
But my Web Api is running on "http://localhost:4000/" .

So while we try to access the wep api from the application then we will get an error regarding the CORS . So to make enable the Web Api to accept the request we have to add this few lines of code in WebApiConfig file .

 Please add this code inside the Register method.


var cors = new EnableCorsAttribute("http://localhost:61375/", "*", "*");
config.EnableCors(cors);

 If you want to allow any request to the Web Api then you can write the following lines of code.


var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);

Note :
If you have not installed the "Microsoft.AspNet.WebApi.Cors" plugins then please install it by the Package managers.

Thanks a lot . Please add your comments to improve my articles.

Comments

Popular posts from this blog

Unable to load one or more breakpoints in Visual studio.

The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

The transaction is aborted or Failure while attempting to promote transaction.