C# 在托管环境中会话超时时间很短?测试会话的丢失?

C# 在托管环境中会话超时时间很短?测试会话的丢失?,c#,session,hosting,session-timeout,C#,Session,Hosting,Session Timeout,在我的托管环境中,我的会话超时时间非常短,有时甚至是2秒,它们会超时 如果用户继续使用网站,会话将被重置,除非会话=null且计数为0 会话应在20分钟后超时,然后将用户重定向到登录页面 代码如下: protected override void OnInit(EventArgs e) { if (this.Session != null && this.Session.Count > 0) { string email = (string)

在我的托管环境中,我的会话超时时间非常短,有时甚至是2秒,它们会超时

如果用户继续使用网站,会话将被重置,除非会话=null且计数为0

会话应在20分钟后超时,然后将用户重定向到登录页面

代码如下:

protected override void OnInit(EventArgs e)
{
    if (this.Session != null && this.Session.Count > 0)
    {
        string email = (string)this.Session["Email"];
        int practiceId = (int)this.Session["PracticeId"];
        int practitionerId = (int)this.Session["PractitionerId"];

        this.ClientScript.RegisterHiddenField("loggedInUserName", email);
        this.ClientScript.RegisterHiddenField("practiceId", practiceId.ToString());
        this.ClientScript.RegisterHiddenField("practitionerId", practitionerId.ToString());
    }
    else
    {    
        this.Session.Abandon();
        Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
        Response.Redirect("~/Default.aspx");    
    }

    base.OnInit(e);
}
有人知道为什么我的会话超时会这么短吗? 当使用我的网站时,有时我可以在没有超时的情况下移动2-5分钟,其他时间10秒,我可以暂停。什么会导致会话丢失,他们有没有避免或测试会话丢失的方法


提前感谢。

我假设您正在覆盖页面的init函数,但每次加载页面时可能放弃会话可能会导致更多问题,而不是解决问题。我将检查母版页中是否存在会话:

protected void Page_Init(object sender, EventArgs e)
{
    if (!HttpContext.Current.User.Identity.IsAuthenticated)
    {
        // user is not logged in
        string ReturnUrl = HttpContext.Current.Request.Url.PathAndQuery;
        string RedirectUrl = "/Login.aspx";
        if (!String.IsNullOrEmpty(ReturnUrl))
        {
            RedirectUrl += "?ReturnUrl=" + Server.UrlEncode(ReturnUrl);
        }
        Response.Redirect(RedirectUrl);
    }
}
如果这在母版页中,它将检查将用户重定向到登录页的每个请求(对从母版继承的aspx页发出的请求)

如果您的应用程序正在共享应用程序池,则您可能正在与其他应用程序共享cookie id:

<authentication mode="Forms">
    <forms loginUrl="~/Login.aspx" timeout="60" name="MY_COOOKIE_NAME" slidingExpiration="true" />
</authentication>
<sessionState timeout="60" />

MY COOKIE名称将标识您的应用程序使用的COOKIE,其他应用程序可能具有默认COOKIE名称,因此您的会话虽然显然已验证,但不属于该应用程序,因为它们将被其他应用程序覆盖。滑动过期意味着每次访问页面时会话时间都会延长

此外,请检查machineKey配置元素是否存在,这使我的会话更加稳定:

<machineKey 
validationKey="random_validation_key" 
decryptionKey="random_decryption_key" 
validation="SHA1" decryption="AES" />