How to get custom header value in Web API 2 MVC 5 handler?

get custom header value in Web API 2 MVC 5 handler

Table of Contents
  1. $.ajax call with header request.
  2. API controller with added route-prefix, route and AustomAuthFilter attribute.
  3. Authorization filter attribute.
  4. get custom header value using request header.

This is the API base url as given below.

var baseURL = "localhost://3456/API/BusinessEntity/GetBusinessEntityDetailByID/1";

The $.ajax call with header request

 $.ajax({
            url: baseURL,
            type: "POST",           
            data: {},
            beforeSend: function (xhr) {
                xhr.setRequestHeader("UserType", "admin");
            },
            async: true,
            cache: false,
            success: function (data) {
            }
     });

API Controller with CustomAuthFilter attribute

namespace PCX.API
{
    [RoutePrefix("API/BusinessEntity")]
    [CustomAuthFilter]
    public class BusinessEntityController : BaseAPIController
    {
        [Route("GetBusinessEntityDetailByID/{costcenterid}")]
        public IHttpActionResult GetBusinessEntityDetailByID(int CostCenterID)
        {          
            List<string> lCostCenterName = new BusinessEntityRepository().GetCostCenterWithCodeByID(CostCenterID);

            return Json(lCostCenterName);
        }
    }
}

Get custom header value using request header

namespace PCX.Portal.Api
{
    public class CustomAuthFilter : AuthorizationFilterAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
            {
                var FilePath = System.Web.HttpContext.Current.Request.FilePath;
                IEnumerable<string> headerValues = actionContext.Request.Headers.GetValues("UserType").FirstOrDefault();           
            }
        }
    }
}

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 Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.