如何从会话中检索会话变量?

时间:2015-01-28 09:14:16

标签: asp.net-mvc session

我想在控制器中创建会话:

Session["UserName"] = username

在我的其他控制器中,我想要检索此名称,但是当我写道时:

string username = (string)Session["UserName"]

它是" null"

为什么会这样?

[HttpPost]
    public ActionResult Login(LogOnModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            string[] per = MvcA.Controllers.RuleUsers.ValidateUserAndRole(model.UserName, model.Password);
            if (per[0]=="true")

            {
                Session["Role"]=per[1];
                Session["UserName"] = model.UserName;

                if (Url.IsLocalUrl(returnUrl))
                {
                    return Redirect(returnUrl);
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {
                ModelState.AddModelError("", "Wrong");
            }
        }
        return View(model);
    }    


  public ActionResult Add(SellsLiveAdd Per)
    {
        string ses = (string)(Session["UserName"]);
.....

修改

为什么有时我可以检索Session [" UserName"],有时这个变量不存在。发生了什么?

1 个答案:

答案 0 :(得分:0)

您使用的是HttpSessionStateBase Controller.Session吗?

尝试使用System.Web.HttpContext.Current.Session["UserName"]

进一步检查配置中的<sessionState timeout="9999" />

希望这有帮助。

相关问题