.net MVC使用Session验证用户登录

Posted Walter_lee2008

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了.net MVC使用Session验证用户登录相关的知识,希望对你有一定的参考价值。

用最简单的Session方式记录用户登录状态

1.添加DefaultController控制器,重写OnActionExecuting方法,每次访问控制器前触发

public class DefaultController : Controller
    
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        
            base.OnActionExecuting(filterContext);
            var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;

            var userName = Session["UserName"] as String;
            if (String.IsNullOrEmpty(userName))
            
                //重定向至登录页面
                filterContext.Result = RedirectToAction("Index", "Login", new  url = Request.RawUrl);
                return;
            

        
    
2.登录控制器
public class LoginController : Controller
    
        // GET: Login
        public ActionResult Index(string ReturnUrl)
        
            if (Session["UserName"] != null)
            
                return RedirectToAction("Index", "Home");
            
            ViewBag.Url = ReturnUrl;
            return View();
        

        [HttpPost]
        public ActionResult Index(string name, string password, string returnUrl)
        
            /*
                添加验证用户名密码代码
            */
            Session["UserName"] = name;
            if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\\\"))
            
                return Redirect(returnUrl);
            
            else
            
                return RedirectToAction("Index", "Home");
            
        

        // POST: /Account/LogOff
        [HttpPost]
        public ActionResult LogOff()
        
            Session["UserName"] = null;
            return RedirectToAction("Index", "Home");
        
    

3.需要验证的控制器继承DefaultController

public class HomeController : DefaultController
    
        public ActionResult Index()
        
            return View();
        
    

4.设定session过期时间,由于session的默认时间是20分钟,timeout即为过期时间,设定webconfig.xml文件如下:

  <system.web>
    <sessionState mode="InProc" timeout="1" />
  </system.web>


以上是关于.net MVC使用Session验证用户登录的主要内容,如果未能解决你的问题,请参考以下文章