22

I'm converting ASP.NET web application to MVC Web Api project. One of my methods expects HttpRequest class. However, Web Api controller holds only HttpRequestMessage (this.Request) object. Do you know how I can convert HttpRequestMessage to HttpRequest?

tereško
  • 58,060
  • 25
  • 98
  • 150
Avi L
  • 1,558
  • 2
  • 15
  • 33

2 Answers2

27

You probably don't need to convert from HttpRequestMessage. There is another way:

var context = new HttpContextWrapper(HttpContext.Current);
HttpRequestBase request = context.Request;
Boris Lipschitz
  • 9,236
  • 5
  • 53
  • 63
  • 4
    System.Web.HttpContext.Current.Request – sobelito Feb 25 '14 at 20:32
  • 3
    This seems awfully like cheating to me but I'm forced to do it if I want to write functions that can be called from ASP.NET Web API controllers as well as ASP.NET MVC controllers. For the life of me I don't understand by web API couldn't just be built on top of MVC (so ApiController could be a subclass of a normal MVC Controller). Instead if you want to use MVC and API together you have to navigate between two parallel but incompatible worlds with the same concepts in each. – Andy Jul 07 '16 at 16:01
  • 2
    I've seen on the comments under [another answer](https://stackoverflow.com/questions/9565889/get-the-ip-address-of-the-remote-host#10998580) that you shouldn't use System.Web.HttpContext.Current in Web API projects - you can instead use `(HttpContextWrapper)Request.Properties["MS_HttpContext"]` – OutstandingBill Jun 13 '18 at 11:53
-1

Try to use/create a HttpRequestWrapper using your HttpRequestBase.

Real Programmer
  • 331
  • 2
  • 13
  • How do I get an 'HttpRequestBase'? should I create one myself? (i.e. create new object and copy 'HttpRequestMessage' parameters to it) – Avi L Apr 30 '13 at 10:41
  • 1
    you can get HttpRequestBase using `((HttpContextWrapper)Request.Properties["MS_HttpContext"]).Request` – M. Jahedbozorgan Feb 08 '19 at 16:22