Accessing HTTP Request from ASP.NET Web API
Note: This post refers to .NET Framework for Windows only, and not for the cross-platform .NET Core or simply .NET as it is re-branded in 2020. This means this post is outdated for newer version of .NET
Do you need access to the bare HTTP request in ASP.NET Web API to access custom header etc.? Then add the HttpRequestMessage:
public class CalculatorController : ApiController
{
public int Add(HttpRequestMessage requestMessage, int x, int y)
{
var accessToken = requestMessage.Headers.Authorization.Parameter;
// use the HTTP header
return x + y;
}
}
The HttpRequestMessage
is automatically bound to the controller action, so you can still execute the action like http://localhost/calculator/add?x=3&y=2
Simple and easy.
Comments