22

What is the correct way to access a header value in a WebApi2 controller? I have method that looks like this:

    [Route(Name ="Stuff")]
    public SysDataTablePager Get(string sEcho, int iDisplayStart)

It returns paged json data to a jquery DataTable.

I am trying to this to get the search value.

var nameFilter = Convert.ToString(Request["sSearch_1"]);

But I am getting this error:

Cannot apply indexing with [] to an expression of type 'System.Net.Http.HttpRequestMessage'

2 Answers 2

38

Try this

IEnumerable<string> headerValues;
var nameFilter= string.Empty;
if (Request.Headers.TryGetValues("sSearch_1", out headerValues))
{
    nameFilter = headerValues.FirstOrDefault();
}
Sign up to request clarification or add additional context in comments.

2 Comments

Headers is a collection inside the Request object. You need to access it how you would access a member from a collection. If this worked for you,please accept it as answer
Or you can use [FromHeader] on your action parameter, which will extract it directly from you request header automatically.
8

Using ASP.Net Core Web Application (.Net Core) for a web api project.

Try this

//check the header
StringValues headerValues;
var nameFilter = string.Empty;
if (Request.Headers.TryGetValue("X-Custom-Token", out headerValues)) {
  //validate the token
  nameFilter = headerValues.FirstOrDefault();
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.