How to add and get Header values in WebApi

asp.net-mvc, asp.net-mvc-4, asp.net-web-api, c#, c#-4.0

Solution

On the Web API side, simply use Request object instead of creating new HttpRequestMessage

var re = Request;
var headers = re.Headers;

if (headers.Contains("Custom"))
{
    string token = headers.GetValues("Custom").First();
}

return null;

Output -

Problem

I need to create a POST method in WebApi so I can send data from application to WebApi method. I'm not able to get header value. Here I have added header values in the application: ``` using (var client = new WebClient()) { // Set the header so it knows we are sending JSON. client.Headers[HttpRequestHeader.ContentType] = "application/json"; client.Headers.Add("Custom", "sample"); // Make the request var response = client.UploadString(url, jsonObj); } ``` Following the WebApi post method: ``` public string Postsam([FromBody]object jsonData) { HttpRequestMessage re = new HttpRequestMessage(); var headers = re.Headers; if (headers.Contains("Custom")) { string token = headers.GetValues("Custom").First(); } } ``` What is the correct method for getting header values? Thanks.

Original source