How to add and get Header values in WebApi

user2652077 picture user2652077 · Jan 28, 2014 · Viewed 252k times · Source

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.

Answer

ramiramilu picture ramiramilu · Jan 28, 2014

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 -

enter image description here