18

Both have Request and Response properties, but I can't write a method that takes either HttpContext or HttpContextBase. In some places either one or the other is available so I need to handle both. I know HttpContextWrapper can convert in one direction, but still... why is it like this?

JoelFan
  • 37,465
  • 35
  • 132
  • 205
  • 5
    I came here to figure out how to convert a `HttpContextBase` to `HttpContext`. Your question contained the answer. The answer is `HttpContextWrapper` which derives from `HttpContextBase` and takes a `HttpContext` as a parameter to the constructor. So as the name implies, it wraps a `HttpContext` and makes it available as a `HttpContextBase`-compatible object. Thanks! – René Nov 26 '12 at 11:58
  • http://stackoverflow.com/a/4567707/955831 – Jason Foglia Feb 07 '14 at 15:53

2 Answers2

25

HttpContext has been around since .NET 1.0. Because of backward compatibility reasons, they can't change that class. HttpContextBase was introduced in ASP.NET MVC to allow for better testability because it makes it easier to mock/stub it.

Sander Rijken
  • 21,376
  • 3
  • 61
  • 85
-1

This is an old question but I just had the same problem and the answer is in Gunder's comment.

Create you methods to use HttpContectBase and then wrap your context in a HttpContextWrapper when you want to call it from your code

public class SomeClass{
    ... other stuff in your class
public void MyMethod(HttpContextBase contextbase){
    ...all your other code 
  }
}

Usage

var objSomeClass = new SomeClass();
objSomeClass.MyMethod(new HttpContextWrapper(HttpContext.Current));

I think HttpContext.Current will be null if you make this call via ajax, I will investigate how to get the context and update this post.

Obi
  • 3,091
  • 4
  • 34
  • 56