找回密码
 会员注册
查看: 163|回复: 0

ASP.NET Core 中简单Session登录校验

[复制链接]

1389

主题

5

回帖

496万

积分

管理员

积分
4962990
发表于 2024-2-29 08:52:53 | 显示全部楼层 |阅读模式

ASP.NET Core 中简单Session登录校验:从Session的配置添加、到请求过滤、再到页面操作。推荐相关阅读:ASP.NET 会话状态概述  ASP.NET Cookie 概述  ASP.NET 状态管理建议 ASP.NET Core 中的会话和应用状态

目录

添加Session配置服务

启用Session配置

添加用户模型

添加登录控制器

控制器基础类

登录页面视图

项目结构与测试


添加Session配置服务

配置session超时时间30分钟。

  1. // This method gets called by the runtime. Use this method to add services to the container.
  2. public void ConfigureServices(IServiceCollection services)
  3. {
  4. services.Configure<CookiePolicyOptions>(options =>
  5. {
  6. // This lambda determines whether user consent for non-essential cookies is needed for a given request.
  7. options.CheckConsentNeeded = context => true;
  8. options.MinimumSameSitePolicy = SameSiteMode.None;
  9. });
  10. services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
  11. // 添加用户Session服务
  12. //services.AddSession();
  13. services.AddSession(options =>
  14. {
  15. options.IdleTimeout = TimeSpan.FromMinutes(30);
  16. options.Cookie.HttpOnly = true;
  17. });
  18. // 指定Session保存方式:分发内存缓存
  19. services.AddDistributedMemoryCache();
  20. }
复制代码

启用Session配置

注意放置代码的顺序,Session必须在MVC之前。

  1. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  2. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  3. {
  4. if (env.IsDevelopment())
  5. {
  6. app.UseDeveloperExceptionPage();
  7. }
  8. else
  9. {
  10. app.UseExceptionHandler("/Home/Error");
  11. app.UseHsts();
  12. }
  13. app.UseHttpsRedirection();
  14. //使用静态文件
  15. app.UseStaticFiles();
  16. //Cookie策略
  17. //app.UseCookiePolicy();
  18. //Session
  19. app.UseSession();
  20. app.UseMvc(routes =>
  21. {
  22. routes.MapRoute(
  23. name: "default",
  24. // template: "{controller=Home}/{action=Index}/{id?}");
  25. //template: "{controller=Home}/{action=Server}/{id?}");
  26. template: "{controller=Login}/{action=SignIn}/{id?}");
  27. });
  28. }
复制代码

添加用户模型

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. namespace RTVSWeb.Models
  7. {
  8. public class UserModel
  9. {
  10. [Required(ErrorMessage = "用户名不能为空")]
  11. public string Username { get; set; }
  12. [Required(ErrorMessage = "密码不能为空")]
  13. [DataType(DataType.Password)]
  14. public string Password { get; set; }
  15. public bool RememberMe { get; set; }
  16. }
  17. }
复制代码

添加登录控制器

此类提供登录校验和退出。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using Microsoft.AspNetCore.Mvc;
  6. using RTVSWeb.Models;
  7. using RTVSWeb.Utils;
  8. // For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
  9. namespace RTVSWeb.Controllers
  10. {
  11. public class LoginController : Controller
  12. {
  13. // GET: /<controller>/
  14. public IActionResult SignIn(UserModel userModel)
  15. {
  16. if (ModelState.IsValid)
  17. {
  18. //检查用户信息
  19. if (userModel.Username.Equals("rtvsweb") && userModel.Password.Equals("cvnavi2018"))
  20. {
  21. //记录Session
  22. HttpContext.Session.Set("User", ByteConvertHelper.Object2Bytes(userModel));
  23. //跳转到系统首页
  24. return RedirectToAction("Server", "Home");
  25. }
  26. ViewBag.ErrorInfo = "用户名或密码错误";
  27. return View(userModel);
  28. }
  29. ViewBag.ErrorInfo = ModelState.Values.First().Errors[0].ErrorMessage;
  30. return View(userModel);
  31. }
  32. public IActionResult SignOut()
  33. {
  34. //清除Session
  35. HttpContext.Session.Clear();
  36. //跳转到系统登录界面
  37. return RedirectToAction("SignIn", "Login");
  38. }
  39. }
  40. }
复制代码

控制器基础类

此类是提供给其他需要登录验证的Controller进行继承。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using Microsoft.AspNetCore.Mvc;
  6. using Microsoft.AspNetCore.Mvc.Filters;
  7. // For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
  8. namespace RTVSWeb.Controllers
  9. {
  10. public class BaseController : Controller
  11. {
  12. /// <summary>
  13. /// 请求过滤处理
  14. /// </summary>
  15. /// <param name="filterContext"></param>
  16. public override void OnActionExecuting(ActionExecutingContext filterContext)
  17. {
  18. byte[] result;
  19. filterContext.HttpContext.Session.TryGetValue("User", out result);
  20. if (result == null)
  21. {
  22. filterContext.Result = new RedirectResult("/Login/SignIn");
  23. return;
  24. }
  25. base.OnActionExecuting(filterContext);
  26. }
  27. }
  28. }
复制代码

登录页面视图

/Login/SignIn.cshtml

  1. @{
  2. Layout = null;
  3. }
  4. @model UserModel
  5. <!DOCTYPE html>
  6. <html>
  7. <head>
  8. <title>系统登录</title>
  9. <!-- Tell the browser to be responsive to screen width -->
  10. <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
  11. <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css">
  12. <link rel="stylesheet" href="~/lib/font-awesome/css/font-awesome.css">
  13. <link rel="stylesheet" href="~/css/AdminLTE.css">
  14. <link rel="stylesheet" href="~/lib/icheck/skins/square/blue.css">
  15. </head>
  16. <body class="hold-transition login-page">
  17. <div class="login-box">
  18. <div class="login-logo">
  19. <b>RTVS Web服务管理</b>
  20. </div>
  21. <!-- /.login-logo -->
  22. <div class="login-box-body">
  23. <p class="login-box-msg">系统登录校验</p>
  24. <!-- <div asp-validation-summary="All" class="text-danger"></div> -->
  25. <form asp-controller="Login" asp-action="SignIn" method="post">
  26. <span class="text-danger">@ViewBag.ErrorInfo</span>
  27. <div class="form-group has-feedback">
  28. <input asp-for="Username" type="text" class="form-control" placeholder="用户名">
  29. <span class="glyphicon glyphicon-user form-control-feedback"></span>
  30. <span asp-validation-for="Username" class="text-danger"></span>
  31. </div>
  32. <div class="form-group has-feedback">
  33. <input asp-for="Password" type="password" class="form-control" placeholder="密码">
  34. <span class="glyphicon glyphicon-lock form-control-feedback"></span>
  35. </div>
  36. <div class="row">
  37. <div class="col-xs-8">
  38. <div class="checkbox icheck">
  39. <label>
  40. <input asp-for="RememberMe" type="checkbox"> 记住我
  41. </label>
  42. </div>
  43. </div>
  44. <!-- /.col -->
  45. <div class="col-xs-4">
  46. <button type="submit" class="btn btn-primary btn-block btn-flat">登录</button>
  47. </div>
  48. <!-- /.col -->
  49. </div>
  50. </form>
  51. </div>
  52. <!-- /.login-box-body -->
  53. </div>
  54. <!-- /.login-box -->
  55. <script src="~/lib/jquery/dist/jquery.js"></script>
  56. <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
  57. <script src="~/lib/icheck/icheck.js"></script>
  58. <script>
  59. $(function () {
  60. $('input').iCheck({
  61. checkboxClass: 'icheckbox_square-blue',
  62. radioClass: 'iradio_square-blue',
  63. increaseArea: '20%' // optional
  64. });
  65. });
  66. </script>
  67. </body>
  68. </html>
复制代码

项目结构与测试

项目结构如下:

 测试效果:

参考文章:http://www.cnblogs.com/fonour/p/5943401.html


来源:https://blog.csdn.net/boonya/article/details/84565976
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?会员注册

×
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 会员注册

本版积分规则

QQ|手机版|心飞设计-版权所有:微度网络信息技术服务中心 ( 鲁ICP备17032091号-12 )|网站地图

GMT+8, 2024-12-26 11:19 , Processed in 0.400475 second(s), 27 queries .

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表