There are certain steps that need to be followed for enabling CORS in ASP.NET Web API :
Step 1: We Have to install the CORS Package, and to install it , open Nuget Package Manager console and type and run command Install-Package Microsoft.AspNet.WebApi.Cors, this will install all the CORS packages.
Step 2: Now in Global.asax file, we define Default Route for the Web API
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
Step 3: Now to enable CORS , we have to add some line of code, just before the Default Route of API in Application_Start() function in Global.asax file
var cors = new System.Web.Http.Cors.EnableCorsAttribute("*", "*", "*");
GlobalConfiguration.Configuration.EnableCors(cors);
Here EnableCorsAttribute takes 3 parameters, which are
- origins (Ex. "http://www.xyz.com")
- headers: "*"
- methods: "*"
Step 4:Now we will define the Controller and Action Method of the Web API, which goes like this
public class ValuesController : ApiController
{
public string Get(string fisrtName, string lastName)
{
return "FullName is : " + fisrtName + ' ' + lastName;
}
}
Note: Here the controller 'ValuesController', must inherits from ApiController, which is already present in MVC, and it provides basic functionalities for making Http request.
0 Comment(s)