Getting the Current HttpRequestMessage Outside of ApiController

By | November 23, 2014

If you’re like me, one of the draws of using a framework like ASP.NET Web API is that it’s designed, from ground up, to be testable.  It’s nice to know that you can test code in isolation without having to worry about getting a real database connection, a real file off of disk, or, in this case, a real Http request.

In a project that I’m working on for a client, I needed to get access to the current HttpRequestMessage object from within a service class.  I could’ve simply passed this value in from the controller, but then there would be a strict dependency in my service on a fully run-time initialized HttpRequestMessage, which is something that I wanted to avoid; I wanted to initialize ONLY that test data that I needed for my unit test.  I already have an IHttpContextService interface I’m using for dependency injection where, at run time, the implementation of this interface can access the HttpContext.Current value.  But I’m specifically looking for the current HttpRequestMessage object.  So, how do we go from the HttpContext.Current singleton, and get an HttpRequestMessage?

It turns out that you can get it from HttpContext.Current, but it’s not exactly obvious how to do it.  The HttpRequestMessage instance is stored in the Items collection of the the HttpContext object, held in HttpContext.Current, under the key name of “MS_HttpRequestMessage”:

This would be in my run-time implementation of the aforementioned IHttpContextService. Now, from within my service class, I can use the HttpRequestMessage instance to get access to things like the files uploaded by a user, the Http Verb used in the request, etc. And as I write my unit tests, I can prepare a mocked HttpRequestMessage with ONLY those values I need for a given test.

2 thoughts on “Getting the Current HttpRequestMessage Outside of ApiController

  1. Kevin Finck

    Just who is this Portland code monkey . . . ?!

    Nice write-up amigo. Could add:
    TL;DR (HttpRequestMessage)HttpContext.Current.Items[“MS_HttpRequestMessage”];

    😀

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.