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:
Add a reference to
System.Web.Import the
System.Webnamespace.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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access