python ruby-programming-language Smalltalk Vue.js Knockoutjs TypeScript JavaScript, OOPs JavaScript Angular 7, Interview Questions Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 4 Angular 2 AngularJs 1.x NodeJs Perl Programming R Programming RequireJs Rust Programming Backbonejs closure programming language go-programming-language kotlin-programming-language
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

Hi there! Welcome to my blog. My name is Anil Singh. I'm a author of this blog. For more detail about me, kindly refer to this link..
My Blogs - http://code-sample.com and http://code-sample.xyz
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like
www.code-sample.com/. Powered by Blogger.
ASK Questions