【问题标题】:session is expiring even sending request to server会话即将到期,甚至向服务器发送请求
【发布时间】:2014-01-17 07:44:45
【问题描述】:

当用户登录时,我将他的 id 存储在会话中,比如Session["id"]。在大多数页面上,我将会话中的 id 存储在一个整数中,并在各种方法中使用它。我检查了 page_load 事件

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["id"] == null)
    {
        Response.Redirect("Home.aspx");
    }
    //code goes here
}

我知道如果没有请求发送到服务器,会话将在 20 分钟后过期。但即使连续发送请求会话过期,我也会在主页上重定向。这是正确的方法还是我应该尝试其他选择。任何帮助将不胜感激。

【问题讨论】:

  • 在 webconfig 文件中设置 SessionTime out 然后尝试
  • 默认会话超时为 20 分钟,但有时我会在 1 分钟内收到过期消息
  • 您确定使用相同的上下文吗?
  • 是的,很确定 pouya
  • 你的应用中有没有做IO操作?

标签: c# asp.net session login


【解决方案1】:

正确的方法是使用membership API,它可以透明地处理所有这些细节。如this explanatory page所示,您可以直接在会员API中使用web.config中的参数设置超时间隔。

希望我能帮上忙!

【讨论】:

  • 感谢您回答 pantelis,直到现在我使用角色基础安全性。我阅读并尝试了
【解决方案2】:

如果对服务器的两次请求之间的间隔超过 20 分钟,那么只有您的会话会过期

【讨论】:

  • 我知道这个 dhananjay 我也提到了这个问题我想知道的是我应该在会话中存储 id 以在用户的​​内容页面中使用
【解决方案3】:

在 ASP.NET 中使用永久用户登录会话 此示例描述了如何在 ASP.NET 中创建永久用户登录会话。示例代码包含一个 ASP.NET MVC4 项目,用于控制用户注册和登录过程。但是您可以在任何类型的 ASP.NET 项目中使用这种技术。但简单来说,您可以使用此代码

该类的功能是向浏览器 cookie 集合添加一个表单身份验证票证,并具有有效期。

public sealed class CookieHelper
{
private HttpRequestBase _request;
private HttpResponseBase _response;

public CookieHelper(HttpRequestBase request, 
HttpResponseBase response)
{
    _request = request;
    _response = response;
}

//[DebuggerStepThrough()]
public void SetLoginCookie(string userName,string password,bool isPermanentCookie)
{
    if (_response != null)
    {
        if (isPermanentCookie)
        {
            FormsAuthenticationTicket userAuthTicket = 
                new FormsAuthenticationTicket(1, userName, DateTime.Now, 
                DateTime.MaxValue, true, password,               FormsAuthentication.FormsCookiePath);
            string encUserAuthTicket = FormsAuthentication.Encrypt(userAuthTicket);
            HttpCookie userAuthCookie = new HttpCookie
                (FormsAuthentication.FormsCookieName, encUserAuthTicket);
            if (userAuthTicket.IsPersistent) userAuthCookie.Expires = 
                    userAuthTicket.Expiration;
            userAuthCookie.Path = FormsAuthentication.FormsCookiePath;
            _response.Cookies.Add(userAuthCookie);
        }
        else
        {
            FormsAuthentication.SetAuthCookie(userName, isPermanentCookie);
        }
    }
}
}

该功能用于登录页面或登录按钮点击控制。在随附的示例项目中,以下函数是在 AccountController 类中编写的。该函数验证用户的登录,然后向浏览器添加一个永久的表单身份验证票。

private bool Login(string userName, string password,bool rememberMe)
{
if (Membership.ValidateUser(userName, password))
{
    CookieHelper newCookieHelper = 
    new CookieHelper(HttpContext.Request,HttpContext.Response);
    newCookieHelper.SetLoginCookie(userName, password, rememberMe);
    return true;
}
else
{
    return false;
}
} 

【讨论】:

    猜你喜欢
    • 2020-11-12
    • 2012-12-20
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 2020-07-08
    • 1970-01-01
    • 2013-10-24
    • 2010-11-25
    相关资源
    最近更新 更多