Search code examples
c#asp.nethttphandlerashx

PreviousPage in .ashx handler


Is it possible to retrieve the equivalent of Page.PreviousPage within a generic .ashx handler, following a cross-page PostBack from an .aspx page?

I need to access some POST values from the Page performing the PostBack and - while I could simply use Request.Form - the values in question come from WebControls and, as such, have rather obscure (and not very robust) names (e.g. ctl00$WebFormsContent$SomeControl$SomeOtherControl$txtWhatever).

I have tried the following:

public void ProcessRequest(HttpContext context)
{
    Page previous = context.PreviousHandler as Page;
    if (previous != null)
        context.Response.Redirect("http://www.google.com");
}

However, this does not work - upon debugging, I can see that context.PreviousPage is null.

Is there a way to retrieve this information and cast it as a Page?


Solution

  • The PreviousHandler will not help you here. To get your HttpHandler to receive a cross-page PostBack, you have to understand the underlying workings of this.

    Refer: Redirecting Users to Another Page

    Cross-page posting is similar to hyperlinks in that the transfer is initiated by a user action. However, in cross-page posting, the target page is invoked using an HTTP POST command, which sends the values of controls on the source page to the target page. In addition, if the source and target page are in the same Web application, the target page can access public properties of the source page. As always, all of the pages in the application can share information stored in session state or application state.

    As will be clear after reading that bit, all the values you are looking for are actually sent to your handler as POST variables.

    You can find them in the context.Request.Params collection.

    Now that you have the request from your page, lets say Page1.aspx in your handler; we need to create an object that can handle and processing this request. This is an instance of your Page1 object.

    string pagePath = "~/Page1.aspx";                   //virtual path to your page
    Type type = BuildManager.GetCompiledType(pagePath); //find the type
    
    //create an object of your page
    Page myPage = (Page)Activator.CreateInstance(type); 
    myPage.ProcessRequest(HttpContext.Current);         //process the request
    

    After you have processed the current request using your object, you will find the Controls collection is populated and filled with the input data. You can now use exposed properties or FindControl to find the necessary controls and fetch input from them.