Search code examples
c#webformsviewstatehttpmodulehttpcontext

Can I access curent page viewstate from httpModule


To avoid the known issue of resending request when user clicks on browser's refresh button,

I decided to add a HttpModule where I override the load_Complete method to redirect the page to itself. I Basically, keep track of HiddenField values, and restore them after the redirect.

This works fine, the problem now is the page's viewstate data is lost after the redirect (which is an expected behaviour).

So, the question is, is there a way that I can access the page's viewstate data before I redirect (like I do for HiddenField controls - which exist in _page.Controls)? perhaps from httpContext?

here is a snippet of my HttpModule:

public void Init(HttpApplication context)
{
    context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
}

void context_PreRequestHandlerExecute(object sender, EventArgs e)
{               
    _httpContext = System.Web.HttpContext.Current;

    if (_httpContext != null) {
        _page = _httpContext.Handler as System.Web.UI.Page;

        if (_page != null) {
            _page.Load += new EventHandler(_page_Load);
            _page.LoadComplete += new EventHandler(_page_LoadComplete);
        }
        else { return; }

    }
    else { return; }
}

void _page_LoadComplete(object sender, EventArgs e)
{       
    if (_page.IsPostBack) {                       
        /*
        I Dump all hiddenfield values in 1 session variable
        */          
        //hoping to do the same for page's ViewState

        _httpContext.Response.Redirect(_httpContext.Request.RawUrl, false);
    }
}

void _page_Load(object sender, EventArgs e)
{   
    if (!_page.IsPostBack) {
        /*
        restore page hiddenfield controls
        */          
        //hoping to do the same for page's ViewState
    }
}

Solution

  • I ended up adding a Base Page class and changing all my pages to inherit from this BasePage.

    inside the Base page I have 2 public methods, logViewState() and restoreViewState(). Basically these methods save ViewState to a Session and restores ViewState from session respectively.

    from _page_Load I call logViewState(), and then from _page_LoadComplete I call logViewState()

    hope this helps somebody.