HttpRequest vs HttpRequestMessage vs HttpRequestBase

Mehmet Ataş picture Mehmet Ataş · Mar 30, 2013 · Viewed 38.5k times · Source

What are differences between these classes in ASP.NET? As I discovered there is no inheritance relationship between these classes.

Below code returns an instance of HttpRequestWrapper which is a HttpRequestBase and has a HttpRequest

HttpRequestMessage request = ...;
HttpRequestBase reqBase = (request.Properties["MS_HttpContext"] as HttpContextWrapper).Request;
// do somthing with reqBase.Cookies

It seems like Microsoft wanted to annoy us while reaching cookies from HttpRequestMessage.

Is it guaranteed that request.Properties["MS_HttpContext"] will never be null?

Or think that an ajax request is handled in an action of ApiController. I can reach IP of the client with two different ways.

var ip = (request.Properties["MS_HttpContext"] as HttpContextWrapper).Request.UserHostAddress

var ip = HttpContext.Current.Request.UserHostAddress

What is the difference between these two?

Or in general, I can access same request/response data such as Cookie, Header, Requestor Info etc. in different ways. When to use which? Can we say something like "if it is an ajax request, HttpRequest is not guaranteed to work properly because of lack of something so for ajax requests we should use HttpRequestMessage instead"?

Answer

Filip picture Filip · Apr 4, 2013

HttpRequest is present on the Page and UserControl classes as a GET-only property. Similarly, most of its own properties are also GET-only (see 1). This class is used by ASP.NET pages to get information about the incoming http request, e.g. read the client IP, cookies, the query string, whatnot. Importantly, it is part of the "Old" System.Web assembly, which has been around since .NET 1.1

HttpRequestMessage, on the other hand, is new in .NET 4.5. It is part of System.Net. It can be used both by clients and services to create, send and receive requests and responses over HTTP. It replaces HttpWebRequest, which is obsolete in .NET 4.5

On HttpRequestBase and HttpRequestWrapper, best I can do is to just quote the docs

The HttpRequestWrapper class derives from the HttpRequestBase class and serves as a wrapper for the HttpRequest class. This class exposes the functionality of the HttpRequest class and exposes the HttpRequestBase type. The HttpRequestBase class enables you to replace the original implementation of the HttpRequest class in your application with a custom implementation, such as when you perform unit testing outside the ASP.NET pipeline.