Nov 9, 2015

Enable Cross-Origin Requests CORS in ASP.NET Web API

For enabling the CORS request in the ASP.NET Web API project, we have to download the cors package from the Nuget, i.e., Microsoft.AspNet.WebApi.Cors.

Open up the Nuget Package Manager console from the Visual Studio Tools Option —> Library Package Manager —> Package Manager Console.

nuget package
Type the following command to install Cors Package:

Install-Package Microsoft.AspNet.WebApi.Cors

The above CORS package installs, along with any dependencies, into the ASP.NET Web API WebService project. Now open the file App_Start/WebApiConfig.cs and add the following code to the WebApiConfig.Registermethod.

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 }
            );
        }
    }
}


Next, add the [EnableCors] attribute to the Controller class, as follows:

Enable Cors Per Controller

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

namespace WebAPI.Controllers
{
    [EnableCors(origins: "http://www.vamsi.com", headers: "*", methods: "*")]
    public class APIHomeController : ApiController
    {
       Public string Get(int id)
       {
           return "value";
       }
    }
}



If you set [EnableCors] attribute controller class, then it will apply action result methods.
For disabling the Cors, set the [DisableCors] attribute for the particular controller or action method.

Enable Cors Per Action


namespace WebAPI.Controllers
{
    public class APIHomeController : ApiController
    {
      [EnableCors]
      Public string Get(int id)
       {
           return "value";
       }
    } 
}

For Enable Cors for the Entire ASP.NET Web API Project


public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var cors = new EnableCorsAttribute("www.vamsi.com", "*", "*");
        config.EnableCors(cors);
    }
}

No comments:

Post a Comment