How to add and get Header values in WebApi

306,780

Solution 1

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

Solution 2

Suppose we have a API Controller ProductsController : ApiController

There is a Get function which returns some value and expects some input header (for eg. UserName & Password)

[HttpGet]
public IHttpActionResult GetProduct(int id)
{
    System.Net.Http.Headers.HttpRequestHeaders headers = this.Request.Headers;
    string token = string.Empty;
    string pwd = string.Empty;
    if (headers.Contains("username"))
    {
        token = headers.GetValues("username").First();
    }
    if (headers.Contains("password"))
    {
        pwd = headers.GetValues("password").First();
    }
    //code to authenticate and return some thing
    if (!Authenticated(token, pwd)
        return Unauthorized();
    var product = products.FirstOrDefault((p) => p.Id == id);
    if (product == null)
    {
        return NotFound();
    }
    return Ok(product);
}

Now we can send the request from page using JQuery:

$.ajax({
    url: 'api/products/10',
    type: 'GET',
    headers: { 'username': 'test','password':'123' },
    success: function (data) {
        alert(data);
    },
    failure: function (result) {
        alert('Error: ' + result);
    }
});

Hope this helps someone ...

Solution 3

As someone already pointed out how to do this with .Net Core, if your header contains a "-" or some other character .Net disallows, you can do something like:

public string Test([FromHeader]string host, [FromHeader(Name = "Content-Type")] string contentType)
{
}

Solution 4

Another way using a the TryGetValues method.

public string Postsam([FromBody]object jsonData)
{
    IEnumerable<string> headerValues;

    if (Request.Headers.TryGetValues("Custom", out headerValues))
    {
        string token = headerValues.First();
    }
}   

Solution 5

For .NET Core:

string Token = Request.Headers["Custom"];

Or

var re = Request;
var headers = re.Headers;
string token = string.Empty;
StringValues x = default(StringValues);
if (headers.ContainsKey("Custom"))
{
   var m = headers.TryGetValue("Custom", out x);
}
Share:
306,780
Admin
Author by

Admin

Updated on October 22, 2021

Comments

  • Admin
    Admin over 2 years

    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.

  • Aidanapword
    Aidanapword almost 8 years
    Can you not use string token = headers.GetValues("Custom").FirstOrDefault();? Edit: Just noticed you were matching original Qs style.
  • Aidanapword
    Aidanapword almost 8 years
    Answering my own Q: No. The headers.GetValues("somethingNotFound") throws an InvalidOperationException.
  • Si8
    Si8 over 7 years
    Do I use beforeSend in JQuery ajax to send the header?
  • Si8
    Si8 over 7 years
    Perfect... I used the beforeSend and it worked. Awesome :) +1
  • lohiarahul
    lohiarahul almost 7 years
    what is the type of the Request variable and can I access it inside the controller method ? I am using web api 2. What namespace do I need to import?
  • Ð..
    Ð.. over 6 years
    @lohiarahul I believe that is the Fetch API : developer.mozilla.org/en-US/docs/Web/API/Request
  • thepirat000
    thepirat000 over 5 years
    Content-Type is not a valid C# identifier
  • Karthikeyan P
    Karthikeyan P over 3 years
    "if (headers.Contains("Custom"))" not worked. So, I have added like, "if (headers.AllKeys.Contains("Custom"))".
  • Deepak paramesh
    Deepak paramesh about 3 years
    I am sending the header value as x-publisher, how should I handle it.
  • Deepak paramesh
    Deepak paramesh about 3 years
    Thanks this is what I was searching for !