[c#] How to add and get Header values in WebApi

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.

This question is related to c# asp.net-mvc asp.net-mvc-4 c#-4.0 asp.net-web-api

The answer is


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

https://docs.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}";
}

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

try these line of codes working in my case:

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

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


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

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

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)
{
}

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


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"];

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to asp.net-mvc-4

Better solution without exluding fields from Binding How to remove error about glyphicons-halflings-regular.woff2 not found When should I use Async Controllers in ASP.NET MVC? How to call controller from the button click in asp.net MVC 4 How to get DropDownList SelectedValue in Controller in MVC Return HTML from ASP.NET Web API There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country Return JsonResult from web api without its properties how to set radio button checked in edit mode in MVC razor view How to call MVC Action using Jquery AJAX and then submit form in MVC?

Examples related to c#-4.0

Xml Parsing in C# EPPlus - Read Excel Table How to add and get Header values in WebApi How to make all controls resize accordingly proportionally when window is maximized? How to use jquery or ajax to update razor partial view in c#/asp.net for a MVC project How to get first record in each group using Linq How to get first object out from List<Object> using Linq ASP.Net MVC - Read File from HttpPostedFileBase without save .NET NewtonSoft JSON deserialize map to a different property name Datetime in C# add days

Examples related to asp.net-web-api

Entity Framework Core: A second operation started on this context before a previous operation completed FromBody string parameter is giving null How to read request body in an asp.net core webapi controller? JWT authentication for ASP.NET Web API Token based authentication in Web API without any user interface Web API optional parameters How do I get the raw request body from the Request.Content object using .net 4 api endpoint How to use a client certificate to authenticate and authorize in a Web API HTTP 415 unsupported media type error when calling Web API 2 endpoint The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located