VaryByCustom 不适用于会话变量

Posted

技术标签:

【中文标题】VaryByCustom 不适用于会话变量【英文标题】:VaryByCustom not working for session variable 【发布时间】:2011-05-10 12:09:34 【问题描述】:

我正在为带有登录系统的网站使用输出缓存。我有每个用户都可以访问的全局页面。这些页面被缓存并使用母版页。

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

我将用户登录详细信息存储在会话中。我的 global.asax 文件在这里:

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;

我在母版页中有一个面板,对经过身份验证的用户可见。当用户登录并查看公共页面 A 时,另一个访客用户还会在页面 A 上看到经过身份验证的用户面板。如果访客首先查看页面 A,则经过身份验证的用户不会在页面 A 上看到面板。

我的代码的哪一部分有问题?我是第一次使用VaryByCustom。

编辑

我已经像这样修改了我的 global.asax,但文本文件中没有写入任何内容:

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】:

我认为 Session["UserID"] 可能出于某种原因总是返回 null / 或有时返回 null,即使用户已通过身份验证。

在此函数请求之前仔细检查您是否设置了它。

【讨论】:

我看到会话变量已更改,但问题是 GetVaryByCustomString 未触发/我认为无法正常工作 @hasanGursoy 是的,某处有问题,但如果调用了Function,则没有设置会话参数。 什么都试过了,但似乎 Session 在被缓存页面varybycustom请求时不可用,它只适用于用户控件。 @HasanGursoy 所以我对会议是正确的!尝试获取会话的 cookie。与您尝试的想法相同。 我无法使用 cookie 进行用户身份验证。所以我在所有页面都禁用了缓存。

以上是关于VaryByCustom 不适用于会话变量的主要内容,如果未能解决你的问题,请参考以下文章

Volley 请求不适用于 Django 会话

APIUrl 前缀不适用于 Azure APIM

NSURLSessionConfiguration timeoutIntervalForRequest 似乎不适用于后台会话

Codeigniter 会话不适用于 PHP 7

PHP会话不适用于多个WordPress页面

插入不适用于 SQLAlchemy 数据库会话