Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Header Values in WebApi 2 Controller

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'

like image 647
andy Avatar asked Jan 15 '15 19:01

andy


People also ask

How do I get HTTP header values from a controller action?

It’s already possible of course to get access to HTTP header values in ASP.NET MVC or Web API controllers – the direct approach, as below, is to use Request.Headers within a controller action. There are some hoops to jump through though, since the header may not exist, and might have multiple values:

What are the characteristics of web API controller?

Web API Controller Characteristics 1 It must be derived from System.Web.Http.ApiController class. 2 It can be created under any folder in the project's root folder. ... 3 Action method name can be the same as HTTP verb name or it can start with HTTP verb with any suffix (case in-sensitive) or you can apply Http verb attributes ... More items...

Is WebAPI really that bad?

Say what you will about how nice WebAPI is, but a few things in the internal APIs are not exactly clean to use. If you decide you want to access a few of the simple Request collections like Headers, QueryStrings or Cookies, you'll find some pretty inane and inconsistent APIs to retrieve values from them.

What are API headers and how to retrieve them?

These headers are useful means of storing metadata like credentials, secured tokens, custom headers,version details if following API versioning through content negotiation, There are many ways to retrieve header values. In this article, we will see a very simple approach to retrieve the same.


2 Answers

Try this

IEnumerable<string> headerValues;
var nameFilter= string.Empty;
if (Request.Headers.TryGetValues("sSearch_1", out headerValues))
{
    nameFilter = headerValues.FirstOrDefault();
}
like image 158
su8898 Avatar answered Oct 23 '22 19:10

su8898


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();
}
like image 23
Marvin Glenn Lacuna Avatar answered Oct 23 '22 19:10

Marvin Glenn Lacuna