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

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

目录

添加Session配置服务

启用Session配置

添加用户模型

添加登录控制器

控制器基础类

登录页面视图

项目结构与测试


添加Session配置服务

配置session超时时间30分钟。


        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // 添加用户Session服务
            //services.AddSession();
            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(30);
                options.Cookie.HttpOnly = true;
            });
            // 指定Session保存方式:分发内存缓存
            services.AddDistributedMemoryCache();
        }

启用Session配置

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


        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            //使用静态文件
            app.UseStaticFiles();
            //Cookie策略
            //app.UseCookiePolicy();
            //Session
            app.UseSession();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                   // template: "{controller=Home}/{action=Index}/{id?}");
                   //template: "{controller=Home}/{action=Server}/{id?}");
                   template: "{controller=Login}/{action=SignIn}/{id?}");
            });
        }

添加用户模型

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace RTVSWeb.Models
{
    public class UserModel
    {
        [Required(ErrorMessage = "用户名不能为空")]
        public string Username { get; set; }

        [Required(ErrorMessage = "密码不能为空")]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        public bool RememberMe { get; set; }
    }
}

添加登录控制器

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using RTVSWeb.Models;
using RTVSWeb.Utils;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace RTVSWeb.Controllers
{
    public class LoginController : Controller
    {
        // GET: //
        public IActionResult SignIn(UserModel userModel)
        {
            if (ModelState.IsValid)
            {
                //检查用户信息
                if (userModel.Username.Equals("rtvsweb") && userModel.Password.Equals("cvnavi2018"))
                {
                    //记录Session
                    HttpContext.Session.Set("User", ByteConvertHelper.Object2Bytes(userModel));
                    //跳转到系统首页
                    return RedirectToAction("Server", "Home");
                }
                ViewBag.ErrorInfo = "用户名或密码错误";
                return View(userModel);
            }
            ViewBag.ErrorInfo = ModelState.Values.First().Errors[0].ErrorMessage;
            return View(userModel);
        }

        public IActionResult SignOut()
        {
            //清除Session
            HttpContext.Session.Clear();
            //跳转到系统登录界面
            return RedirectToAction("SignIn", "Login");
        }
      
    }
}

控制器基础类

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace RTVSWeb.Controllers
{
    public class BaseController : Controller
    {
        /// 
        /// 请求过滤处理
        /// 
        /// 
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            byte[] result;
            filterContext.HttpContext.Session.TryGetValue("User", out result);
            if (result == null)
            {
                filterContext.Result = new RedirectResult("/Login/SignIn");
                return;
            }
            base.OnActionExecuting(filterContext);
        }
    } 
}

登录页面视图

/Login/SignIn.cshtml

@{
    Layout = null;
}
@model UserModel



    系统登录
    
    
    
    
    
    


    
    
    
    
    
    

项目结构与测试

项目结构如下:

ASP.NET Core 中简单Session登录校验_第1张图片

 测试效果:

ASP.NET Core 中简单Session登录校验_第2张图片

ASP.NET Core 中简单Session登录校验_第3张图片

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

你可能感兴趣的:(ASP.NET)