How to resolve the Cross Origin Resource Sharing (CORS) issue in Asp.net WebAPI?

 Posted by Rajnilari2015 on 9/19/2015 | Category: ASP.NET Web API Interview questions | Views: 1113 | Points: 40
Answer:

Cross Origin Resource Sharing (CORS) allows the server to share the resources being requested by the client application by overcoming the problem of same-origin policy. It is a very common requirement while developing the Asp.net WebAPI applications at the time of deployment where an external client application will try to access the resources by sitting at a different domain where as the resources are available at some other domain and that causes the root issue. CORS overcomes this issue by providing the needed permission for accessing the different domains. The below step will tell us how to do so -


Step a)

Use NuGet Package manager console and add CORS library to the project

e.g.
Install-Package Microsoft.AspNet.WebAPI.Cors -Version 5.0.1


Step b)

Open the file App_Start/WebApiConfig.cs and add the following code to the WebApiConfig.cs method

using System;	


//add the below namespaces

using System.Web.Http;
using System.Web.Http.Cors;

namespace MyWebAPI
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services

//add the below lines

config.EnableCors();
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

.....................................
.....................................

}
}
}


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response