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

            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
    public class BusinessEntityController : BaseAPIController
        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 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 -
My Books - Book 1 and Book 2 Powered by Blogger.