如何在MVC 5上设置会话变量过期时间
本文关键字:会话 变量 过期 时间 设置 MVC | 更新日期: 2023-09-27 18:26:21
我需要为登录生成一个验证码,如:11599。
用户登录时必须输入正确的号码。
但我的默认会话过期时间是30分钟。
我不想让验证码过期这么久。我只需要它只保持1分钟。那么,我如何仅为验证码会话变量设置过期超时?
更新1:
我不想更改全局会话的过期时间。我只需要仅为登录前的"验证码"会话变量设置。
没有内置的方法,但可以非常简单地实现:
Session[name] = value;
//now add a cleanup task that will run after the specified interval
Task.Delay(expireAfter).ContinueWith((task) => {
Session.Remove(name);
});
我把它包装成了一个非常方便的"会话扩展程序"类源代码,你可以这样使用它:
//store and expire after 5 minutes
Session.AddWithTimeout("key", "value", TimeSpan.FromMinutes(5));
PS。如果你仍然使用旧的.NET版本(没有异步代码,没有任务),你会在我的博客文章中找到一个兼容的版本。
对不起,伙计们,我终于使用了这个解决方案:
当生成验证码时,我会将其保存到会话
Session["VerificationCode"] = code;
大家都知道。但是时间怎么样?我把它改成
Session["VerificationCode"] = code;
Session["VerificationTime"] = DateTime.Now;
现在会话中的时间也节省了。然后我可以在用户登录时找到它:
// Verification Code Expired
if ((DateTime)Session["VerificationTime"]).AddMinutes(1) < DateTime.Now)
{
ModelState.AddModelError("VerificationCode", "Verification Code Expired!");
return View(adminLogin);
}
// Verification Code Error
if (Session["VerificationCode"].ToString().ToUpper() != adminLogin.VerificationCode.ToUpper())
{
ModelState.AddModelError("VerificationCode", "Verification Code Error");
return View(adminLogin);
}
您应该创建一个存储在SessionState中的类或结构,而不仅仅是存储验证代码本身。这将使您能够轻松地检查代码和代码的过期日期。
例如:
public class VerificationCode {
public string Code { get; set; }
public DateTime ExpirationDate { get; set; }
}
// in your method
VerificationCode newCode = new VerificationCode {
Code="1559",
ExpirationDate = System.DateTime.Now.AddMinutes(1)
};
Session["VerificationCode"] = newCode;
// in the method where you check the expiration date and code...
VerificationCode code = (VerificationCode)Session["VerificationCode"];
// you can remove the verification code after pulling it out, as you only need
// it once, regardless of whether it is still good or expired.
Session.Remove("VerificationCode");
if (code.ExpirationDate < System.DateTime.Now){
// the verification code expired...
// can remove the verification code after successful login
Session.Remove("VerificationCode");
} else {
// verification code is still good.
// Log the user in?
// can remove the verification code after successful login
Session.Remove("VerificationCode");
}
更新-添加了在过期或成功登录时从会话中删除验证码。-会话变量的方括号访问器。以前使用的VB(doh!)语法(括号)
您不能为某个特定情况更改会话时间。相反,您可以使用带有absoluteExpiration
参数的Cache.Add方法将VerificationCode
存储在Cache
中。
MemoryCache.Default.Add([UserIdentity], [Verification Code],
new DateTimeOffset().ToOffset(TimeSpan.FromMinutes(1)));
然后从Cache
中获取
var verificationCode = MemoryCache.Default.Remove([UserIdentity]);
会话状态设置
默认情况下,ASP.NET使用cookie来标识哪些请求属于特定会话。如果cookie不可用,则可以通过在URL中添加会话标识符来跟踪会话。要禁用cookie,请设置sessionState cookieless="true".
。但这将更改应用程序可用的所有会话的设置。
<configuration>
<system.web>
<sessionState mode="StateServer" cookieless="false" timeout="120"/>
</system.web>
</configuration>
参考文献:http://msdn.microsoft.com/en-us/library/ms525473%28v=vs.90%29.aspx
在你的情况下,你可以使用cookie来跟踪并设置它在1分钟后过期,我可以给你一个例子,比如:
Response.Cookies["userName"].Value = "patrick";
Response.Cookies["userName"].Expires =DateTime.Now.AddMinutes(1);
HttpCookie aCookie = new HttpCookie("lastVisit");
aCookie.Value = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);