VaryByCustom not working for session variable

2.9k views Asked by At

I'm using output cache for a web site with login system. I have global pages which can be accessed by every user. These pages are cached and also use a master page.

<%@ OutputCache Duration="3600" VaryByParam="none" VaryByCustom="userid" %>

I'm storing user login details in a session. My global.asax file is here:

public override string GetVaryByCustomString(HttpContext context, string arg)
{
    string result = String.Empty;
    if (arg == "userid")
    {
        object o = Session["UserID"];
        if (o != null) { result = o.ToString(); }
    }
    else { result = base.GetVaryByCustomString(context, arg); }
    return result;
}

I have a panel in master page which is visible for authenticated users. When a user logins and views public page A another guest user also sees authenticated user panel on page A. If guest first view page A then authenticated user does not see panel on page A.

What part of my code is wrong? I'm using VaryByCustom for first time.

EDIT

I've modified my global.asax like this but nothing is written in the text file:

public override string GetVaryByCustomString(HttpContext context, string arg)
{
    string result = String.Empty;

    FileInfo t = new FileInfo(Server.MapPath("App_Data\\debug.txt"));
    StreamWriter Tex = t.AppendText();
    Tex.WriteLine("GetVaryByCustomString: " + arg);

    if (arg == "userid")
    {
        object o = Session["UserID"];
        if (o != null) { result = o.ToString(); }

        Tex.WriteLine("Checked UserID: " + o + Tex.NewLine);            
    }
    else { result = base.GetVaryByCustomString(context, arg); }

    Tex.Close();

    return result;
}
1

There are 1 answers

5
Aristos On

I think that probably the Session["UserID"] for some reason always return null / or some times return null, even if the user is authenticated.

Double check that you set it before this function ask for it.