views:

758

answers:

3

In ASP.NET , How can i retrieve a cookie value in the Session_End event of global.asax file ? The following code is throwing an exception "Object reference not set to an instance of an object"

    string cookyval = "";
    try
    {
        cookyval = Context.Request.Cookies["parentPageName"].Value;
    }
    catch (Exception ex)
    {
        cookyval = "";
    }

Any advice ?

A: 

Not sure this is possible.

The request is no longer alive at the point the Session_End fires.

Sorry,

Dan

Daniel Elliott
+2  A: 

The Session_End event is fired by the IIS worker process, not an HTTP request. Therefore your HttpContext will be null and you won't be able to set a client's cookie.

See this blog post for more details: http://www.vikramlakhotia.com/Mystries%5Fof%5Fwhen%5Fdoes%5FSession%5FEnd%5Fevent%5Ffires%5Fin%5FAspNet.aspx

Hope this helps.

Paul Suart
A: 

Session_End isn't run in the context of a user request, so there's no access to cookies (or any other request variables).

If you put the value into Session, I think you can access that:

string cookyval = "";
try
{
    cookyval = (string)Session["parentPageName"];
}
catch (Exception ex)
{
    cookyval = "";
}

Otherwise, you'd need to write it to some other server side storage (like a database).

Mark Brackett