日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

asp.net core后台系统登录的快速构建

發布時間:2023/12/4 asp.net 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 asp.net core后台系统登录的快速构建 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

登錄流程圖

示例預覽

構建步驟

當然,你也可以直接之前前往coding倉庫查看源碼,要是發現bug記得提醒我啊~?LoginDemo地址

1. 首先你得有一個項目

2. 然后你需要一個登錄頁面

完整Login.cshtml視圖代碼戳這里-共計55行
效果預覽圖

<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>登錄界面</title><meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no"><link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"><style type="text/css">body { color: #fff; font-family: "微軟雅黑"; font-size: 14px; background: url('https://dn-coding-net-production-pp.qbox.me/96ec8cc7-0e5f-4217-b853-4a88c15579f3.png') no-repeat; }.wrap1 { position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; height: 450px; }/*把整個屏幕真正撐開--而且能自己實現居中*/.main_content { background: url(https://dn-coding-net-production-pp.qbox.me/2ed70a05-04ad-4ccf-81d4-bc1fad2b6e41.png) repeat; margin-left: auto; margin-right: auto; text-align: left; float: none; border-radius: 8px; }.form-group { position: relative; }.login_btn { display: block; background: #3872f6; color: #fff; font-size: 15px; width: 100%; line-height: 50px; border-radius: 3px; border: none; }.login_input { width: 100%; border: 1px solid #3872f6; border-radius: 3px; line-height: 40px; padding: 2px 5px 2px 30px; background: none; }.icon_font { position: absolute; top: 12px; left: 10px; font-size: 18px; color: #3872f6; }.font16 { font-size: 16px; }.mg-t20 { margin-top: 20px; }@media (min-width:200px) {.pd-xs-20 { padding: 20px; }}@media (min-width:768px) {.pd-sm-50 { padding: 50px; }}#grad { background: -webkit-linear-gradient(#4990c1, #52a3d2, #6186a3); /* Safari 5.1 - 6.0 */ background: -o-linear-gradient(#4990c1, #52a3d2, #6186a3); /* Opera 11.1 - 12.0 */ background: -moz-linear-gradient(#4990c1, #52a3d2, #6186a3); /* Firefox 3.6 - 15 */ background: linear-gradient(#4990c1, #52a3d2, #6186a3); /* 標準的語法 */ }/*==jquery.validate css==*/.field-validation-error { color: #e14430 !important; padding-top: 5px; }.input-validation-error { border-color: #d38e99; }</style></head><body><div class="container wrap1"><h2 class="mg-b20 text-center">后臺管理系統</h2><div class="col-sm-8 col-md-5 center-auto pd-sm-50 pd-xs-20 main_content"><p class="text-center font16">用戶登錄</p><form asp-action="Login" method="post" ><div class="form-group mg-t20"><i class="icon_font glyphicon glyphicon-user"></i><input type="text" class="login_input" asp-for="UserName" placeholder="請輸入用戶名" autofocus /><span asp-validation-for="UserName"></span></div><div class="form-group mg-t20"><i class="icon_font glyphicon glyphicon-lock"></i><input type="password" class="login_input" asp-for="UserPwd" placeholder="請輸入密碼" /><span asp-validation-for="UserPwd"></span></div><div class="checkbox mg-b25 hide"><label><input type="checkbox">記住我的登錄信息 ? ? ? ? ? ? ? ? ? ?</label></div><button type="submit" class="login_btn">登 錄</button></form></div></div></body></html>

3. 然后你需要一個登錄的控制器AccountController

控制器里面至少擁有一個呈現登錄頁的action,一個接收登錄請求的action,一個退出的action
·登錄· 判斷是否存在用戶,將用戶名或者用戶ID加密后記錄到cookie中,跳轉到管理頁
·退出· 將cookie移出掉,跳轉到登錄頁
加密的方法可自行切換為其他的加密方法

? ?public class AccountController : Controller{ ? ?
? ?? ?private readonly IUserService _userService; ?
? ?? ?? ?
? ??public AccountController(IUserService userService) ? ? ? ?{_userService = userService;} ? ? ?
? ??
? ?? ?public IActionResult Login() ? ? ? ?{ ? ? ?
? ?? ? ? ?return View();}
? ?? ? ? ?[HttpPost][ValidateAntiForgeryToken] ?public IActionResult Login(AccountModel model) ? ? ? ?{ ? ? ? ? ? ?//驗證模型是否正確if (!ModelState.IsValid){
? ?? ? ? ?return View(model);} ? ? ? ? ?
? ?? ? ? ?//調用服務驗證用戶名密碼if (!_userService.Login(model.UserName, model.UserPwd)){ModelState.AddModelError(nameof(model.UserPwd), "用戶名或密碼錯誤"); ? ? ? ? ? ? ? ?return View();} ? ? ? ? ?
? ?? ? ? ?//加密用戶名寫入cookie中,AdminAuthorizeAttribute特性標記取出cookie并解碼除用戶名var encryptValue = _userService.LoginEncrypt(model.UserName, ApplicationKeys.User_Cookie_Encryption_Key);HttpContext.Response.Cookies.Append(ApplicationKeys.User_Cookie_Key, encryptValue); ? ? ? ? ? ?return Redirect("/");} ? ? ? ?
? ?? ? ? ?public IActionResult Logout() ? ? ? ?{HttpContext.Response.Cookies.Delete(ApplicationKeys.User_Cookie_Key); ? ? ? ? ? ?return Redirect(WebContext.LoginUrl);}}

4. 然后還需要一個身份驗證的特性標記AdminAuthorizeAttribute

本文只是簡單的驗證是否登錄,關于更復雜的權限驗證可參考文章:http://www.cnblogs.com/morang/p/7606843.html,以及示例項目
將此特性標記加到需要的地方即可在訪問時驗證用戶是否登錄,未登錄則跳轉到登錄頁。

? ?public class AdminAuthorizeAttribute : Attribute, IAuthorizationFilter{ ? ? ? ?public void OnAuthorization(AuthorizationFilterContext filterContext) ? ? ? ?{ ? ? ? ? ? ?if (string.IsNullOrEmpty(WebContext.AdminName)){ ? ? ? ? ? ? ? ?if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest"){filterContext.Result = new JsonResult("未登錄");} ? ? ? ? ? ? ? ?else{filterContext.Result = new RedirectResult("Account/Login");} ? ? ? ? ? ? ? ?return;}}}

上面特性標記代碼中的WebContext.AdminName是如何取到的呢?還需要結合如下代碼

? ?//服務定位器public static class ServiceLocator{ ? ? ?
? ??public static IServiceProvider Instance { get; set; } ? ? ?
? ??
? ?? ?public static T GetService<T>() where T : class{ ? ? ? ? ? ?return Instance.GetService<T>();}} ?
? ?? ??//一些通用的信息public static class WebContext{ ? ? ?
? ?? ???public static string AdminName{ ? ? ? ?
? ?? ???? ?get{ ? ? ? ? ? ? ? ?//獲取cookievar hasCookie = ServiceLocator.GetService<IHttpContextAccessor>().HttpContext.Request.Cookies.TryGetValue(ApplicationKeys.User_Cookie_Key, out string encryptValue); ? ? ? ? ? ?
? ?? ???? ? ? ?if (!hasCookie || string.IsNullOrEmpty(encryptValue)) ? ? ? ? ? ? ? ? ? ?return null; ? ? ? ? ? ? ?
? ?? ???? ? ? ? ?var adminName = ServiceLocator.GetService<IUserService>().LoginDecrypt(encryptValue, ApplicationKeys.User_Cookie_Encryption_Key); ? ? ? ? ? ? ? ?return adminName;}} ? ? ?
? ?
? ? ?public const string LoginUrl = "/account/login";} ?
? ? ??//全局的一些Key值public class ApplicationKeys{ ? ? ?
? ? ???public const string User_Cookie_Encryption_Key = "User_Cookie_Encryption_Key"; ? ? ?
? ? ????public const string User_Cookie_Key = "User_Cookie_Key";} ? ?
? ? ????//Startuppublic void ConfigureServices(IServiceCollection services) ? ?{services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();//用于獲取請求上下文services.AddTransient<IUserService, UserService>();services.AddMvc();} ? ?public void Configure(IApplicationBuilder app, IHostingEnvironment env) ? ?{ ? ? ? ?//app.UseMvc()..//最末的時候賦值ServiceLocator.Instance = app.ApplicationServices;}

代碼說明

  • 首先定義了一個存放服務的靜態對象:ServiceLocator

  • 在程序啟動后將IApplicationBuilder.ApplicationServices賦值給ServiceLocator.Instance,這樣就能夠在任何地方使用ServiceLocator.Instance獲取到注入的服務
    (為了更好的獲取實例添加了一個T GetService<T>()方法)

  • 在WebContext中取獲取Cookie值:ServiceLocator.GetService<IHttpContextAccessor>().HttpContext.Request.Cookies

  • 解密獲取的cookie得到用戶名:ServiceLocator.GetService<IUserService>().LoginDecrypt(encryptValue, ApplicationKeys.User_Cookie_Encryption_Key);

  • 所以在后臺就能使用WebContext.AdminName獲取到當前登錄用戶名,或者根據用戶名獲取登錄信息

  • 總結

    • 自定義特性標記和過濾器之間差開一個IFilterMetadata,換言之:特性標記實現了IFilterMetadata就等于是個過濾器(個人理解)

    • asp.net core中模型綁定使用asp-for

    • asp.net core注入服務: 在?Startup.ConfigureServices方法中注入?services.AddTransient<IUserService, UserService>()

    • asp.net core獲取HttpContext對象 參考:ASP.NET Core開發之HttpContext

      ASP.NET Core中提供了一個IHttpContextAccessor接口,HttpContextAccessor?默認實現了它簡化了訪問HttpContext。
      它必須在程序啟動時在IServicesCollection中注冊,這樣在程序中就能獲取到HttpContextAccessor,并用來訪問HttpContext。
      services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    • asp.net core中表單直接使用form標簽,asp-action,asp-controller等指定路由參數即可,并且能夠自動生成防偽字段標識,配合ValidateAntiForgeryToken特性標記預防CSRF?代碼生成比較圖
      相關文檔地址:https://docs.microsoft.com/zh-cn/aspnet/core/security/anti-request-forgery

    • autofocus屬性 可使文本框自動獲取焦點

    Demo下載地址

    • 點擊下載Demo

    • Coding倉庫地址克隆代碼:git clone https://git.coding.net/yimocoding/WeDemo.git -b LoginDemo LoginDemo

    探索學習中,若有錯誤或者不足指出還望園友指出。

    原文地址:http://www.cnblogs.com/morang/p/7614537.html


    .NET社區新聞,深度好文,微信中搜索dotNET跨平臺或掃描二維碼關注

    總結

    以上是生活随笔為你收集整理的asp.net core后台系统登录的快速构建的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。