Enabling Cross in Web API 2

Enabling Cross-Origin Requests in ASP.NET Web API 2

Let’s enabling the CORS request in the ASP.NET Web API project, we need to add the CORS package from the Nuget using Nuget Package Manager i.e. 
-        Microsoft.AspNet.WebApi.Cors

Type the following command to install CORS Package –
-        Install-Package Microsoft.AspNet.WebApi.Cors

We can configure CORS support for the Web API at three levels -
1.     Enable CORS at the Global Level
2.     Enable CORS at the Controller Level
3.     Enable CORS at the Action Level

Now open the file App_Start/WebApiConfig.cs and add the following code to the WebApiConfig.Register method.
//WebApiConfig
//Register Enable Cors Attribute in WebApiConfig file.
using System.Web.Http;
using System.Web.Http.Cors;
namespace Demo.EnableCors
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            //Enable Cors Attribute
            var cors = new EnableCorsAttribute(origins: "http://localhost:53865,http://code-sample.com", headers: "*", methods: "*");
            config.EnableCors(cors);

            // Web API configuration and services
            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApiWithAction",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

// WebApiConfig Register in the Global.asax.cs Application_Start method.
public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
}

//Enable CORS at the Global level
- To enable CORS for all Web API controllers in your application, pass an EnableCors Attribute instance to the Enable CORS method.
//CORS support - Global level
using System.Web;
using System.Web.Http;
using System.Web.Http.Cors;
namespace Demo.EnableCors.Api
{
    [EnableCors(origins: "http://localhost:53865,http://code-sample.com", headers: "*", methods: "*")]
    public class BaseAPIController : ApiController
    {
        /// BaseAPIController constructor will check that identity exists or not.
        public BaseAPIController()
        {
            if (!(HttpContext.Current.User.Identity.IsAuthenticated))
            {
                SetHeader();
            }
        }

        /// Set header status code to 401
        public void SetHeader()
        {
            HttpResponse resp = HttpContext.Current.Response;
            resp.StatusCode = 401;
            resp.End();
        }
    }
}

//Enable CORS at the Controller level
//CORS support - Controller level
using System.Web;
using System.Web.Http;
using System.Web.Http.Cors;
namespace Demo.EnableCors.Api
{
    [EnableCors(origins: "http://localhost:53865, http://code-sample.com", headers: "*", methods: "*")]
    public class UserController : ApiController
    {
        [HttpGet]
        [Route("GetUsers")]
        public bool GetUsers(Guid? Id)
        {
            return _repoUser.GetUsers(Id);
        }
    }
}

//Enable CORS at the Action level
//CORS support - Action level
using System.Web;
using System.Web.Http;
using System.Web.Http.Cors;
namespace Demo.EnableCors.Api
{   
    public class UserController : ApiController
    {
        [HttpGet]
        [Route("GetUsers")]
        [EnableCors(origins: "http://localhost:53865, http://code-sample.com", headers: "*", methods: "*")]
        public bool GetUsers(Guid? Id)
        {
            return _repoUser.GetUsers(Id);
        }
    }
}

References –

I hope you are enjoying with this post! Please share with you friends. Thank you so much!
ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

Enabling Cross-Origin Requests in ASP.NET Web API 2 Enabling Cross-Origin Requests in ASP.NET Web API 2 Reviewed by Anil Singh on 2:38 AM Rating: (5)
www.code-sample.com/. Powered by Blogger.
^