zoukankan      html  css  js  c++  java
  • 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");
            }
  • 相关阅读:
    for循环中的作用域 闭包
    for,forEach,for in ,for of,$.each和$().each应用
    交换变量的值
    URL和URI的关系
    Delphi Idhttp.Get方法
    Delphi 时间转换异常处理(各Win系统时间显示格式不同)
    Delphi 接口统一方法
    Delphi 高级停靠(Dock)技术的实现[转载]
    delphi 客户端_动态装载插件DLL
    ADOQuery导出Excel超快(大量数据)!
  • 原文地址:https://www.cnblogs.com/KKSoft/p/7242469.html
Copyright © 2011-2022 走看看