web api enable cors

Jacob
Jacob
Member
56 Points
13 Posts

Hi,

I am working on web api 2.0. It's working fine in the same domain i.e in same origin. But I want to call from another domain.

How do I enable cors (cross origin resource sharing)?

Views: 10061
Total Answered: 1
Total Marked As Answer: 1
Posted On: 09-Oct-2015 04:33

Share:   fb twitter linkedin
Answers
Rahul Maurya
Rahul M...
Teacher
4822 Points
23 Posts
         

Hi Jacob,

You can enable CORS in Web API in following steps:


I) add the CORS NuGet package=> In Visual Studio, from the Tools menu, select Library Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command: Install-Package Microsoft.AspNet.WebApi.Cors (This command will install the latest package and updates all dependencies, including the core Web API libraries. The CORS package requires Web API 2.0 or later.)


II) open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace MvcApplication4
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}

 

III) add the [EnableCors] attribute to the Controller class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;
namespace MvcApplication4.Controllers
{
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class Default1Controller : ApiController
{
 
// Controller method
}
}

 

 

 

Posted On: 20-Oct-2015 00:00
 Log In to Chat