Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

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

0.00/5 (No votes)
9 Feb 2015 2  
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

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.Register method.

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.venkatbaggu.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

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

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.venkatbaggu.com", "*", "*");
        config.EnableCors(cors);
    }
}

The post Enable Cross-Origin Requests CORS in ASP.NET Web API appeared first on Venkat Baggu Blog.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here