We need a NuGet package Microsoft.AspNet.WebApi.Cors to enable CORS in Web API. So let us first 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
using System.Web.Http; namespace WebService { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // New code config.EnableCors(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
ValuesController
class:
using System.Net.Http; using System.Web.Http; using System.Web.Http.Cors; namespace WebService.Controllers { [EnableCors(origins: "*", headers: "*", methods: "*")] public class ValuesController : ApiController { // Controller methods not shown... } }
Redeploy the updated Web API application. You don’t need to update WebClient. Now the AJAX request from WebClient should succeed. The GET, PUT, and POST methods are all allowed.
Add comment