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

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Google Amazon and Flipkart Book Store!

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.
ASK Questions
SQL Server NodeJs TypeScript JavaScript Angular SQL Server My Book