mberube.Net
mberube.Net

Reputation: 2170

Get access to the request (HttpRequestMessage) in a WebAPI constructor

I need to get access to the request (of type HttpRequestMessage) in the constructor of an ApiController. Unfortunately, at this stage of the object creation, the Request property isn't initialized yet and the HttpContext.Current.Request contains the request in the "old" class format (HttpRequest).

Is there a way to access the HttpRequestMessage during controller construction ?

Thanks.

Upvotes: 4

Views: 2588

Answers (1)

Kolappan N
Kolappan N

Reputation: 4011

While you cannot access the Http Request in the constructor, it can be accessed using the Initialize method. Here is the code to access the Http Request object via this method

protected override void Initialize(HttpControllerContext controllerContext)
{
   var request = controllerContext.Request;

   base.Initialize(controllerContext);
}

I ran into a situation where I needed JWT token before any function is called and this solution worked well for me.

Note: Make sure to include base.Initialize(controllerContext); to avoid runtime errors.

Upvotes: 3

Related Questions