ASP.NET Core 中簡單Session登入校驗
阿新 • • 發佈:2018-12-05
ASP.NET Core 中簡單Session登入校驗:從Session的配置新增、到請求過濾、再到頁面操作。推薦相關閱讀:ASP.NET 會話狀態概述 ASP.NET Cookie 概述 ASP.NET 狀態管理建議 ASP.NET Core 中的會話和應用狀態
目錄
新增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<CookiePolicyOptions>(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: /<controller>/
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
{
/// <summary>
/// 請求過濾處理
/// </summary>
/// <param name="filterContext"></param>
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
<!DOCTYPE html>
<html>
<head>
<title>系統登入</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" href="~/lib/font-awesome/css/font-awesome.css">
<link rel="stylesheet" href="~/css/AdminLTE.css">
<link rel="stylesheet" href="~/lib/icheck/skins/square/blue.css">
</head>
<body class="hold-transition login-page">
<div class="login-box">
<div class="login-logo">
<b>RTVS Web服務管理</b>
</div>
<!-- /.login-logo -->
<div class="login-box-body">
<p class="login-box-msg">系統登入校驗</p>
<!-- <div asp-validation-summary="All" class="text-danger"></div> -->
<form asp-controller="Login" asp-action="SignIn" method="post">
<span class="text-danger">@ViewBag.ErrorInfo</span>
<div class="form-group has-feedback">
<input asp-for="Username" type="text" class="form-control" placeholder="使用者名稱">
<span class="glyphicon glyphicon-user form-control-feedback"></span>
<span asp-validation-for="Username" class="text-danger"></span>
</div>
<div class="form-group has-feedback">
<input asp-for="Password" type="password" class="form-control" placeholder="密碼">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-8">
<div class="checkbox icheck">
<label>
<input asp-for="RememberMe" type="checkbox"> 記住我
</label>
</div>
</div>
<!-- /.col -->
<div class="col-xs-4">
<button type="submit" class="btn btn-primary btn-block btn-flat">登入</button>
</div>
<!-- /.col -->
</div>
</form>
</div>
<!-- /.login-box-body -->
</div>
<!-- /.login-box -->
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/lib/icheck/icheck.js"></script>
<script>
$(function () {
$('input').iCheck({
checkboxClass: 'icheckbox_square-blue',
radioClass: 'iradio_square-blue',
increaseArea: '20%' // optional
});
});
</script>
</body>
</html>
專案結構與測試
專案結構如下:
測試效果: