我正在尝试使用会话,但是当我调用SetSession方法时,我看到HttpContext.Current为空,因此我从gettor获得MinValue,因为会话属性为空) 如何解决这个问题? 正因为如此,每次我尝试获取会话变量时,它都不起作用,确实 =D 看起来我忘记了一些东西,但是......
当用户连接时,我从控制器调用会话管理器:
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
{
var identityUser = UserManager.FindByEmail(model.Email);
if (identityUser.Matricule.IsNotNull() && !identityUser.Matricule.HasValue)
{
SetAlert("Error");
}
else
{
SessionManager.matricule = identityUser.Matricule.Value;
var user = BL.PersonnelBL.GetAll(SessionManager.matricule);
SessionManager.firstName = user.prenom;
SessionManager.lastName = user.nom;
SessionManager.chainId = user.chaine.chaine;
SessionManager.secteurId = user.chaine.secteur.Id;
SessionManager.serviceId = user.chaine.service.Id;
SessionManager.isAuditor = user.auditTarget.IsNull() ? false : true;
}
// Redirect to local
return RedirectToLocal(returnUrl);
}
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
会话管理器:
public class SessionManager
{
public static int matricule
{
get
{
object property = GetSession("MATRICULE");
if (property != null)
{
return Convert.ToInt32(property);
}
return int.MinValue;
}
set
{
SetSession("MATRICULE", value);
}
}
}
private static bool SetSession(string key, object value)
{
if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
HttpContext.Current.Session[key] = value;
return true;
}
return false;
}
在 Web.Config 中:
<system.web>
...
<sessionState mode="InProc" timeout="45" />
</system.web>
提前致谢
您的HttpContext.Current
可能null
有几个原因:
您正在运行以下代码:
- 在
Task
或其他后台线程中; - 来自
Session_End
事件; - 在不支持会话的
HttpModule
或HttpHandler
中(请参阅IRequiresSessionState
标志界面)。