python ruby-programming-language Smalltalk Vue.js Knockoutjs TypeScript JavaScript, OOPs JavaScript 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
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

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