JoelFan
JoelFan

Reputation: 38714

Why does HttpContext not derive from HttpContextBase?

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?

Upvotes: 19

Views: 4432

Answers (2)

Obi
Obi

Reputation: 3091

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.

Upvotes: -1

Sander Rijken
Sander Rijken

Reputation: 21615

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.

Upvotes: 25

Related Questions