I currently have a message handler in my Web API service that overrides 'SendAsync' as follows:
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
//implementation
}
Within this code I need to inspect a custom added request header value named MyCustomID
. The problem is when I do the following:
if (request.Headers.Contains("MyCustomID")) //OK
var id = request.Headers["MyCustomID"]; //build error - not OK
...I get the following error message:
Cannot apply indexing with [] to an expression of type 'System.Net.Http.Headers.HttpRequestHeaders'
How can I access a single custom request header via the HttpRequestMessage
(MSDN Documentation) instance passed into this overridden method?
Create a new method - 'Returns an individual HTTP Header value' and call this method with key value everytime when you need to access multiple key Values from HttpRequestMessage.
For ASP.NET you can get the header directly from parameter in controller method using this simple library/package. It provides a
[FromHeader]
attribute just like you have in ASP.NET Core :). For example:Try something like this:
There's also a TryGetValues method on Headers you can use if you're not always guaranteed to have access to the header.
One line solution
For ASP.Net Core there is an easy solution if want to use the param directly in the controller method: Use the [FromHeader] annotation.
Additional Info: In my case the "myParam" had to be a string, int was always 0.
modern variant :)