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