VaryByCustom not working for session variable
Asked Answered
A

1

8

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;
}
Ammonal answered 15/11, 2010 at 21:56 Comment(1)
OK, I've found that I cannot access current session variable "Session state is not available in this context.". Trying to fix it now.Ammonal
A
0

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.

Aleman answered 16/11, 2010 at 2:26 Comment(5)
I see that the session variable is changed but problem is GetVaryByCustomString is not fired/work properly I thinkAmmonal
@hasanGursoy Yes somewhere there is the problem, but if the Function is called, then the session parameter is not set.Aleman
Tried everything but it seems Session is not available when it's requested by cached page varybycustom, it only works on user controls.Ammonal
@HasanGursoy So I have right about the Session !. Try just to get the cookie of the session. Is the same think as the one you try.Aleman
I can't use cookies for user authentication. So I've disabled caching at all pages.Ammonal

© 2022 - 2024 — McMap. All rights reserved.