18.1. Accessing HTTP-Specific Information from Within a Class

Problem

You want to create a business service class that can be used by any page in your site, and you want it to have access to the HTTP-specific information available in web pages—that is, all the server objects used by the application.

Solution

Add a reference to the System.Web assembly in your business service project and a companion Imports statement (or using statement in C#) to your class, and then use the Current property of the HttpContext object to access the desired server objects.

In the business service class, use the .NET language of your choice to:

  1. Add a reference to System.Web.

  2. Import the System.Web namespace.

  3. Reference the current HTTP context when accessing server objects, as in HTTPContext.Current.Session.

Example 18-1 and Example 18-2 show the VB and C# class files for an example business service that implements this solution.

Discussion

By referencing the Current property of the HttpContext object in the business class, your code has full access to all the server objects used in web applications. This includes the ability to access all information about the request being made, the response being returned, session data, and application data. For more information, refer to the HttpContext class in the MSDN documentation.

When you create an ASP.NET application with Visual Studio .NET, all the pages and classes of the web project have access to the HTTP-specific information. This is because Visual Studio automatically ...

Get ASP.NET Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.