views:

1066

answers:

6

Hi folks,

inside my ASP.NET MVC controller, I've got a method that requires an HttpRequest object. All I have access to is an HttpRequestBase object.

Is there anyway I can somehow convert this?

What can/should I do??

A: 

Does HttpRequest request = (HttpRequest) theobject; work at all?

Preet Sangha
Nope :( that was the first thing i tried. (eg. HttpReqest requets = (HttpRequest)this.Request; // this == an HttpRequestBase property in the current controller instance.
Pure.Krome
+1  A: 

Typically when you need to access the HttpContext property in a controller action, there is something you can do better design wise.

For example, if you need to access the current user, give your action method a parameter of type IPrincipal, which you populate with an Attribute and mock as you wish when testing. For a small example on how, see this blog post, and specifically point 7.

Tomas Lycken
Totally agreed! problem is, I can't modify the current class library we're required to use .. so this doesn't help me much :(
Pure.Krome
+2  A: 

Is it your method, so you can re-write it to take HttpRequestBase? If not, you can always get the current HttpRequest from HttpContext.Current.HttpRequest to pass on. However, I often wrap access to the HttpContext inside a class like mentioned in ASP.NET: Removing System.Web Dependencies for better unit testing support.

Kevin Hakanson
Embarassingly, I also thought of this and it doesn't work. The HttpContext is the MVC context .. so there is no 'Current' property exposed on it. I'm not sure how to get access to 'oldschool' HttpContext.Current ... ???
Pure.Krome
To be sure you are grabbing the HttpContext class instead of the controller member, try and use System.Web.HttpContext.Current.
Kevin Hakanson
I needed to use the full namespace because it was taking the current MVC namespace property. cheers. Note to others: don't do what i'm doing. it's a VeryBadThing(tm).
Pure.Krome
A: 

Try to use/create a HttpRequestWrapper using your HttpRequestBase.

Klaas
A: 
RogerGales
A: 

Hello,

There is no way to convert between these types.

We had a similar case. We rewrote our classes/web services methods so that they use HttpContextBase, HttpApplicationStateBase, HttpServerUtilityBase, HttpSessionStateBase... instead of the types of close name without the "Base" suffix (HttpContext, ... HttpSessionState). They are a lot easier to handle with home-made mocking.

I feel sorry you couldn't do it.

Barbara Post