HttpContext Class in ASP.Net

Only experienced developers can understand the importance. Anyway, you are reading this article; that implies you have not used HttpContext before and want to learn it. Fine, trust me, a good understanding of HttpContext will provide extra mileage in application development for you.

Let's start slowly, and then we will try to see the property of HttpContext class for authentication.

A HttpContext object holds information about the current HTTP request. If you are familiar with the HTTP request formation pipeline then you understand the information that HttpContext stores. Anyway we will see it practically. The important point is, whenever we make a new HTTP request or response then the Httpcontext object is created. Yes each time it is created it creates a server current state of a HTTP request and response.

It can hold information like, Request, Response, Server, Session, Item, Cache, User's information like authentication and authorization and much more.

As the request is created in each HTTP request, it ends too after the finish of each HTTP request or response.

Now, let's see how to access the HttpRequest class in an ASP.NET page practically.

1. Check request processing time using HttpContext class

This will be our first operation to check the uses of the HttpContext class. In the global.aspx page we know that a BeginRequest() and EndRequest() is executed every time before any Http request. In those events we will set a value to the context object and will detect the request processing time. Here is a sample example.

protected void Application_BeginRequest(object sender, EventArgs e)

        {

HttpContext.Current.Items.Add("Begintime"DateTime.Now.ToLongTimeString());

        }

        protected void Application_EndRequest(object sender, EventArgs e)

        {

            TimeSpan diff = Convert.ToDateTime(DateTime.Now.ToLongTimeString()) -

     Convert.ToDateTime(HttpContext.Current.Items["Begintime"].ToString());

        }

Here is sample output where we are detecting the time taken to finish the request.



2. Access current information using HttpContext class

At this point we will fetch a few properties of the HttpContext class, those properties are set by default when the application has started, and by checking those property we can learn some important information about the current Http request.

  protected void Page_Load(object sender, EventArgs e)

        {

            Response.Write("Request URL"+  HttpContext.Current.Request.Url)          Response.Write("Number of Session variable" + HttpContext.Current.Session.Count);

            Response.Write("current Timestamp" + HttpContext.Current.Timestamp);

            Response.Write("Object in Application level " + HttpContext.Current.Application.Count);

            Response.Write("Is Debug Enable in current Mode?" + HttpContext.Current.IsDebuggingEnabled);

        }




The first line shows the current URL of the HTTP request, the second line shows the number of session variables associated with the current request. Since we did not set any session variable, it's 0. The third line shows the current time with date (this information is useful when we want to log the HTTP request time) then the last two lines show the number of application level objects and check whether the debug mode is active or not.

So, those are the basic properties that we have accessed from the HttpContext class, there are many more that you can access in the same way.

3. Access user's status using Httpcontext class

This is another area where the Httpcontext class plays a useful role. In this example we will implement Window's authentication and we will print the username from the context class. Then we will check the IsAuthenticated property. Have a look at the following example.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

namespace WebAPP

{

    public partial class Index : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            Response.Write("Username" + HttpContext.Current.User.Identity.Name + "<br>");

            Response.Write("Is Authenticated" + HttpContext.Current.User.Identity.IsAuthenticated + "<br>");

            Response.Write("Authentication type" + HttpContext.Current.User.Identity.AuthenticationType + "<br>");

        }

    }

}

In the page_load event we are printing all that information. Please keep in mind that, before going to this experiment you need to implement Windows Authentication in the application, then you will only get the proper value of those properties.



Here is sample output of the above example.

Conclusion

Here we saw a few uses of the HttpContext class, though there are many more than that. To keep the article short we have not explained them here, you can do a little experimentation to understand more about the HttpCntext class.

Up Next
    Ebook Download
    View all
    Learn
    View all