135

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.

12 Answers 12

231

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

7
  • Can you not use string token = headers.GetValues("Custom").FirstOrDefault();? Edit: Just noticed you were matching original Qs style. Jun 9, 2016 at 9:08
  • Answering my own Q: No. The headers.GetValues("somethingNotFound") throws an InvalidOperationException. Jun 9, 2016 at 9:42
  • Do I use beforeSend in JQuery ajax to send the header?
    – Si8
    Jan 30, 2017 at 14:47
  • Perfect... I used the beforeSend and it worked. Awesome :) +1
    – Si8
    Jan 30, 2017 at 14:50
  • 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?
    – lohiarahul
    Jul 27, 2017 at 6:27
26

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 ...

23

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)
{
}
1
  • Thanks this is what I was searching for ! May 17, 2021 at 19:50
15

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();
    }
}   
10

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);
}
8

In case someone is using ASP.NET Core for model binding,

https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding

There's is built in support for retrieving values from the header using the [FromHeader] attribute

public string Test([FromHeader]string Host, [FromHeader]string Content-Type )
{
     return $"Host: {Host} Content-Type: {Content-Type}";
}
2
  • 8
    Content-Type is not a valid C# identifier Dec 15, 2018 at 17:18
  • I am sending the header value as x-publisher, how should I handle it. May 17, 2021 at 19:49
6

try these line of codes working in my case:

IEnumerable<string> values = new List<string>();
this.Request.Headers.TryGetValues("Authorization", out values);
0
4

For WEB API 2.0:

I had to use Request.Content.Headers instead of Request.Headers

and then i declared an extestion as below

  /// <summary>
    /// Returns an individual HTTP Header value
    /// </summary>
    /// <param name="headers"></param>
    /// <param name="key"></param>
    /// <returns></returns>
    public static string GetHeader(this HttpContentHeaders headers, string key, string defaultValue)
    {
        IEnumerable<string> keys = null;
        if (!headers.TryGetValues(key, out keys))
            return defaultValue;

        return keys.First();
    }

And then i invoked it by this way.

  var headerValue = Request.Content.Headers.GetHeader("custom-header-key", "default-value");

I hope it might be helpful

2

A simple function to get a header value, with a "one-liner" variant using TryGetValue:

private string GetHeaderValue(string key) =>
    Request.Headers.TryGetValue(key, out var value)
        ? value.First()
        : null;

var headerValue = GetHeaderValue("Custom");
1
app.MapGet("/", ([FromHeader(Name = "User-Agent")] string data) =>
{
    return $"User agent header is: {data}";
});
0

You need to get the HttpRequestMessage from the current OperationContext. Using OperationContext you can do it like so

OperationContext context = OperationContext.Current;
MessageProperties messageProperties = context.IncomingMessageProperties;

HttpRequestMessageProperty requestProperty = messageProperties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;

string customHeaderValue = requestProperty.Headers["Custom"];
0

For .net Core in GET method, you can do like this:

 StringValues value1;
 string DeviceId = string.Empty;

  if (Request.Headers.TryGetValue("param1", out value1))
      {
                DeviceId = value1.FirstOrDefault();
      }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.