Click here to Skip to main content
15,886,049 members
Articles / Web Development / ASP.NET
Tip/Trick

Passing information to a page using a custom HttpHandler

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
27 Mar 2011CPOL2 min read 20.7K   5  
Instances of pages not accessible like other classes. This demonstrates how to instantiate a page and pass parameters through a custom HttpHandler.
The Page in ASP.NET is not instantiated in the normal way to be used like other classes to pass parameters using getters and setters. But this is possible by using a custom HttpHandler and any parameter can be passed to the Page object.

As the Page class can not be instantiated in the normal way, it has to do its job by itself and this may result in many if..else conditions. Suppose there are some common controls in several pages and they are to be running their business logic as per session parameters. This would involve some complex if..else conditions. Repeating the same code in all the pages is not the best way. In such a situation, the code can be moved to a common place, and that would be an HttpHandler.

Generally, if any logic is to be performed outside a page and then the result passed to the page, you can use a custom HttpHandler.

This code here demonstrates a simple example which helps the reader to understand the flow easier.

Page1 has two hyperlinks to Page2 (Default2.aspx) and Page3 (Default3.aspx). Page1 also sets a parameter in the session.

XML
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/Default2.aspx">Page2
    <asp:HyperLink ID="HyperLink2" runat="server" NavigateUrl="~/Default3.aspx">Page3

C#
protected void Page_Load(object sender, EventArgs e)
{
    Session["loggeduser"] = "Albin";
}

Page2 and Page3 do the same work: check this session variable and display it. On the markup, it simply has two labels. These two pages inherit from a class which inherits from System.Web.UI.Page, the BasePage. This BasePage resides inside the app_code folder, so it makes it accessible to other classes and also this BasePage class can have an inherited hierarchy or other patterns.

C#
// Partial class inherited from Page class which resides in the app_code folder.
public partial  class BasePage:System.Web.UI.Page
{
    // Few properties which are used to set before the page init.
    public string LoggedUser { get; set; }

    public IGreetings greetings { get; set; }
}

public partial class Default2 : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Access the BasePage members and set in the label display
        Label1.Text =LoggedUser +" From Page 2";
        Label2.Text = greetings.GreetingMessage;

    }
}

public partial class Default3 : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //Access the BasePage members and set in the label display
        Label1.Text = LoggedUser + " From Page 3";
        Label2.Text = greetings.GreetingMessage;
    }
}

Now the request for these two pages has to be handled by a custom handler. For that, we need to register the handler in the web.config file.
XML
<httphandlers>
    <add verb="GET" path="Default2.aspx,Default3.aspx" type="CustomPageHandler" />
</httphandlers>

We are only going to handle the request/ GET verb. The path is self explanatory. The type is the class name of the custom handler. Now the code of the custom handler class. IRequireSessionState is just an Identity interface which helps to access the session from the handler.

IRequireSessionState is available in the namespace System.Web.SessionState and the BuildManager class is available from the namespace System.Web.Compilation.

C#
public class CustomPageHandler : IHttpHandler, IRequiresSessionState
{
    public bool IsReusable
    {
        get { return true; }
    }

    public void ProcessRequest(HttpContext context)
    {
        //Instantiate the Page
        string url = context.Request.FilePath;
        BasePage page = BuildManager.CreateInstanceFromVirtualPath(
                             url, typeof(BasePage)) as BasePage;

        //Set the properties through an accessible Page Type, the BasePage class.
        page.LoggedUser = "Welcome "+context.Session["loggeduser"].ToString();

        page.greetings = new EasterGreetings();

        //Page is nothing but a handler by itself
        IHttpHandler handler = page;

        //Context is not avialble by instantiating the page.
        //So pass the context and call the ProcessRequest
        //which process the request and renders the output
        //through the context's response object.
        handler.ProcessRequest(context);
    }
}

This instantiates the corresponding page and passes the parameters. It is easily possible as the pages are inherited from the BasePage class. Here there is a greetings object also passed to the page. It is just a strategy composite.
C#
public interface IGreetings
{
	string GreetingMessage{get; }
}

public class ChristMasGreetings : IGreetings
{

    public string GreetingMessage
    {
        get
        {
            return "Merry Jingles! ";
        }

    }
}

public class EasterGreetings : IGreetings
{

    public string GreetingMessage
    {
        get
        {
            return "Happy Surprises!";
        }

    }
}

public class CricketGreetings : IGreetings
{

    public string GreetingMessage
    {
        get
        {
            return "Keep running between wickets!";
        }

    }
}

That is it. Now you can try this in a real world example when needed.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
I am developer in .Net and GIS. albin_gis@yahoo.com

Comments and Discussions

 
-- There are no messages in this forum --