ASP.NET Core 中簡單Session登入校驗
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>
專案結構與測試
專案結構如下:
測試效果:
相關文章
- Servlet+Session+Cookie登入、校驗、退出的邏輯程式碼ServletSessionCookie
- 【ASP.NET Core】使用最熟悉的Session驗證方案ASP.NETSession
- Asp.net core中RedisMQ的簡單應用ASP.NETRedisMQ
- ASP.NET登入驗證ASP.NET
- flutter - 登陸介面&表單校驗Flutter
- ASP.NET Core之身份驗證和授權Cookie&SessionASP.NETCookieSession
- 基於 Session 實現簡訊登入Session
- Asp.net core 過濾器的簡單使用ASP.NET過濾器
- 華為遊戲登入校驗異常遊戲
- Android需求之RxJava2實現表單校驗(註冊登入)AndroidRxJava
- json web token 實踐登入以及校驗碼驗證JSONWeb
- 一個簡單的身份證校驗
- Django筆記三十二之session登入驗證操作Django筆記Session
- day7-分頁、上傳圖片、session登入、csrf校檢Session
- 【asp.net core 系列】13 Identity 身份驗證入門ASP.NETIDE
- asp.net mvc中的使用者登入驗證過濾器ASP.NETMVC過濾器
- Workflow Core + asp.net core 5.0 實現簡單審批工作流ASP.NET
- CAS單點登入-簡介
- session與登入機制Session
- [譯]簡單的React身份校驗機制React
- .net core 登入全域性驗證過濾器過濾器
- ASP.NET Core 簡單整合簽發 JWT (JSON Web Tokens)ASP.NETJWTJSONWeb
- Asp.Net Core + Ocelot 閘道器搭建:路由簡單配置ASP.NET路由
- ASP.NET CORE 邊學邊記之 SwaggerUI簡單配置ASP.NETSwaggerUI
- 前後端實現登入token攔截校驗後端
- ASP.NET Core Authentication系列(四)基於Cookie實現多應用間單點登入(SSO)ASP.NETCookie
- .Net Core中簡單使用MongoDBMongoDB
- ASP.NET Core Authentication系列(二)實現認證、登入和登出ASP.NET
- ssh免密登入簡單操作
- jwt加meta元資訊實現登入後校驗JWT
- SpringMVC(六) 攔截器和使用者登入校驗SpringMVC
- ASP.NET Core Web Api之JWT VS Session VS Cookie(二)ASP.NETWebAPIJWTSessionCookie
- ASP.NET Core 入門教程 5、ASP.NET Core MVC 檢視傳值入門ASP.NETMVC
- Laravel 通過 cookie 實現基於 session 的單點登入LaravelCookieSession
- 校園門戶登入
- PbootCMS出現登入失敗,表單提交校驗失敗等情況怎麼辦?boot
- 簡單的網頁登入頁面網頁
- uniapp 實現簡訊驗證碼登入APP