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'
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:
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...
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.
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.
Try this
IEnumerable<string> headerValues;
var nameFilter= string.Empty;
if (Request.Headers.TryGetValues("sSearch_1", out headerValues))
{
nameFilter = headerValues.FirstOrDefault();
}
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With