0

From along time i need to ask a question which shouldn't be but please its things around on humans head.

Why MVC has different implementation for Server, Respone, etc that WebForms ?

In MVC depends on :

  • MVC Session HttpSessionStateBase -> came from System.Web
  • MVC Server HttpServerUtilityBase
  • MVC Request HttpRequestBase
  • MVC Respone HttpResponseBase
  • MVC Context HttpContextBase

But in WebForms :

  • WebForms Session HttpSessionState -> came from System.Web.SessionState

  • HttpServerUtility

  • HttpRequest

  • HttpResponse

  • HttpContext

Also in MVC the HttpContext is a property of controller. but in WebForms the HttpContext is just a static class there.

Looks like MVC put Wrappers classes for WebForms one ? or idont know.

HttpSessionStateWrapper

HttpContextWrapper

I just wondered why all of these things are different ? does the specialists who write libraries make it like these for appears nice not ugly ?

kokowawa
  • 35
  • 5

1 Answers1

1

TL;DR

MVC does use HttpRequest, HttpContext, HttpResponse, etc. It just doesn't use them directly.

By depending on the "base" classes it allows you to substitute your own implementations which inherit from those abstract classes. That enables us to write unit tests for controllers or other classes that depend on context, request, etc.

At runtime it takes HttpRequest and wraps it in a class called HttpRequestWrapper which also inherits from HttpRequestBase, since HttpRequest does not inherit from HttpRequestBase. (And the same pattern for the other classes.)


Technically MVC uses the same classes as WebForms at runtime. It just doesn't directly depend on them. Instead it depends on the base classes. At runtime it uses wrapper classes like HttpContextWrapper which inherit from the base class but actually "wrap" an instance of HttpContext, HttpRequest, etc.

By depending on abstract classes like HttpContextBase instead of concrete classes like HttpContext, the MVC framework enables you to "mock" those classes by providing alternate implementations of the abstract classes. Here's a popular answer on that. It's not extremely simple, but at least it's not impossible.

In contrast, unit testing was much more difficult with WebForms. Most of the testing strategy for WebForms involved keeping as much as possible out of them and putting it in other testable classes. But when it came to anything involving the request, response, context, etc., it was difficult. Apparently it wasn't impossible, but you had to do some weird custom stuff in your pages instead of using the Context or Page properties.

Scott Hannen
  • 27,588
  • 3
  • 45
  • 62
  • Why Also in MVC the HttpContext is a property of controller. but in WebForms the HttpContext is just a static class there. – kokowawa Apr 28 '19 at 21:14