MVC中Session的使用和传递

1.登录时在controller中记录session,代码如下:

复制代码
 public ActionResult Login(UserLoginViewModel uViewModel)
        {
            if (ModelState.IsValid)
            {
                var user = db.ADUsers.SingleOrDefault(t => t.usrName == uViewModel.usrName && t.usrPassword == uViewModel.usrPassword);

                if (user != null)
                {
                    FormsAuthentication.SetAuthCookie(uViewModel.usrName, false);//将用户名放入Cookie中
                    System.Web.HttpContext.Current.Session["usrName"] = uViewModel.usrName; //将用户名放入session中

                    return RedirectToAction("Index","Home");
                }
                else
                {
                    ModelState.AddModelError("usrName", "用户名不存在!");
                }
            }
            return View(uViewModel);
        }
复制代码

 

2.在View中,可以根据session进行判断是否正常登录

复制代码
@if (Session["usrName"] != null)
{
    using (Html.BeginForm("LogOff", "ADUsers", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
    {
        @Html.AntiForgeryToken()

        <ul class="nav navbar-nav navbar-right">
            <li>
                @Html.ActionLink("你好," + Session["usrName"] + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
            </li>
            <li><a href="javascript:document.getElementById('logoutForm').submit()">注销</a></li>
        </ul>
    }
}
else
{
    <ul class="nav navbar-nav navbar-right">
        <li>@Html.ActionLink("登录", "Login", "ADUsers", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
        <li>cookies:@Session["usrName"];</li>
    </ul>
复制代码

 

3.注销时,记得将session清空

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            System.Web.HttpContext.Current.Session["usrName"] = null;
            return RedirectToAction("Login");
        }

 

posted @   A·DONG  阅读(12186)  评论(0编辑  收藏  举报
编辑推荐:
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
阅读排行:
· 为DeepSeek添加本地知识库
· 精选4款基于.NET开源、功能强大的通讯调试工具
· DeepSeek智能编程
· [翻译] 为什么 Tracebit 用 C# 开发
· 腾讯ima接入deepseek-r1,借用别人脑子用用成真了~
点击右上角即可分享
微信分享提示