【发布时间】:2015-01-16 08:43:06
【问题描述】:
我正在尝试使用会话,但是当我调用 SetSession 方法时,我看到 HttpContext.Current 为空,所以我得到了 MinValue(来自 gettor,因为会话属性为空)如何解决这个问题?正因为如此,每次我试图获取会话变量时,它都不起作用,确实 =D 看起来我忘记了一些东西但是......
当用户连接时,我从控制器调用 SessionManager:
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 为空,那么您可能没有在活动会话中执行此操作,我的意思是当没有活动请求时。你在做并行处理吗?
-
这段代码在哪里执行?在控制器中,服务?
-
您是否在单独的任务/线程中运行它? HttpContext.Current 不会被复制到工作线程 IIRC。
-
@hazimdikeni:谢谢。这必须工作查看第一个编辑的帖子以查看所有代码:-)
-
@JoeMighty 此代码位于处理所有会话的分离管理器中。查看我对问题的编辑
标签: c# asp.net .net asp.net-mvc asp.net-mvc-4