服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服务器之家 - 编程语言 - ASP.NET教程 - .net MVC使用Session验证用户登录(4)

.net MVC使用Session验证用户登录(4)

2020-05-25 13:57清幽火焰 ASP.NET教程

这篇文章主要为大家详细介绍了.net MVC使用Session验证用户登录的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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.登录控制器

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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

?
1
2
3
4
5
6
7
public class HomeController : DefaultController
  {
    public ActionResult Index()
    {
      return View();
    }
  }

这种方式适合比较小的项目

优点:简单,易开发
缺点:无法记录登录状态,而且Session方式容易丢失

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/pengdylan/p/6421440.html

延伸 · 阅读

精彩推荐