ASP.NET Core 6 (.NET 6) 快速开发简单登陆和登出功能

2024-02-21 05:12

本文主要是介绍ASP.NET Core 6 (.NET 6) 快速开发简单登陆和登出功能,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

ASP.NET Core 6中的简单登录和登出功能,需要使用身份验证和授权中间件实现,

1、添加引用 Microsoft.AspNetCore.Authentication.Cookies

使用Visual Studio 2022或更高版本开发工具,创建一个ASP.NET Core 6 (.NET 6) 项目,项目添加引用 Microsoft.AspNetCore.Authentication.Cookies,引用方法可以参考:

1)使用Nuget界面管理器

搜索 "Microsoft.AspNetCore.Authentication.Cookies" 在列表中分别找到它,点击"安装"

2)使用Package Manager命令安装

PM> Install-Package Microsoft.AspNetCore.Authentication.Cookies

3)使用.NET CLI命令安装

> dotnet add package Microsoft.AspNetCore.Authentication.Cookies

2、项目代码

项目中Program.cs的代码如下:

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using SpiderContent.Data;
using SpiderContent.Utils;
using System.Security.Claims;
using System.Security.Principal;Dictionary<string, string> _accounts = new Dictionary<string, string>();
async Task RenderHomePageAsync(HttpContext context)
{if (context?.User?.Identity?.IsAuthenticated == true){await context.Response.WriteAsync(@"<html><head><title>Index</title></head><body>" +$"<h3>Welcome {context.User.Identity.Name}</h3>" +@"<a href='Account/Logout'>登出</a></body></html>");}else{await context.ChallengeAsync();}
}async Task SignInAsync(HttpContext context)
{if (string.Compare(context.Request.Method, "GET") == 0){await RenderLoginPageAsync(context, null, null, null);}else{var userName = context.Request.Form["username"];var password = context.Request.Form["password"];if (_accounts.TryGetValue(userName, out var pwd) && pwd == password){var principal = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, userName) },CookieAuthenticationDefaults.AuthenticationScheme));await context.SignInAsync(principal);context.Response.Redirect("/");}else{await RenderLoginPageAsync(context, userName, password, "用户名或密码错误!");}}
}
async Task SignOutAsync(HttpContext context)
{await context.SignOutAsync();context.Response.Redirect("/");
}
static Task RenderLoginPageAsync(HttpContext context, string userName, string password, string errorMessage)
{context.Response.ContentType = "text/html";return context.Response.WriteAsync(@"<html><head><title>Login</title></head><body><form method='post'>" +$"<input type='text' name='username' placeholder='用户名' value ='{userName}'/>" +$"<input type='password' name='password' placeholder='密码'  value ='{password}'/> " +@"<input type='submit' value='登陆' /></form>" +$"<p style='color:red'>{errorMessage}</p>" +@"</body></html>");
}var builder = WebApplication.CreateBuilder(args);// Add services to the container.builder.Services.AddAuthentication(options => options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,config=> {config.Cookie.HttpOnly = true;//options.Cookie.SecurePolicy = CookieSecurePolicy.Always;config.Cookie.SameSite = SameSiteMode.Lax;config.Cookie.Name = CookieAuthenticationDefaults.AuthenticationScheme;config.LoginPath = "/Account/Login";});
builder.Services.AddRazorPages();var app = builder.Build();
_accounts.Add("admin", "admin");
_accounts.Add("guest", "guest");
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();app.UseRouting();app.UseAuthentication();app.MapRazorPages();
app.MapControllers();
app.UseEndpoints(endpoints => {endpoints.Map(pattern: "/", RenderHomePageAsync);endpoints.Map("Account/Login", SignInAsync);endpoints.Map("Account/Logout", SignOutAsync);
});
app.Run();

这篇关于ASP.NET Core 6 (.NET 6) 快速开发简单登陆和登出功能的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/730667

相关文章

基于 Cursor 开发 Spring Boot 项目详细攻略

《基于Cursor开发SpringBoot项目详细攻略》Cursor是集成GPT4、Claude3.5等LLM的VSCode类AI编程工具,支持SpringBoot项目开发全流程,涵盖环境配... 目录cursor是什么?基于 Cursor 开发 Spring Boot 项目完整指南1. 环境准备2. 创建

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

C#使用Spire.Doc for .NET实现HTML转Word的高效方案

《C#使用Spire.Docfor.NET实现HTML转Word的高效方案》在Web开发中,HTML内容的生成与处理是高频需求,然而,当用户需要将HTML页面或动态生成的HTML字符串转换为Wor... 目录引言一、html转Word的典型场景与挑战二、用 Spire.Doc 实现 HTML 转 Word1

SpringBoot 多环境开发实战(从配置、管理与控制)

《SpringBoot多环境开发实战(从配置、管理与控制)》本文详解SpringBoot多环境配置,涵盖单文件YAML、多文件模式、MavenProfile分组及激活策略,通过优先级控制灵活切换环境... 目录一、多环境开发基础(单文件 YAML 版)(一)配置原理与优势(二)实操示例二、多环境开发多文件版

使用docker搭建嵌入式Linux开发环境

《使用docker搭建嵌入式Linux开发环境》本文主要介绍了使用docker搭建嵌入式Linux开发环境,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录1、前言2、安装docker3、编写容器管理脚本4、创建容器1、前言在日常开发全志、rk等不同

Debian 13升级后网络转发等功能异常怎么办? 并非错误而是管理机制变更

《Debian13升级后网络转发等功能异常怎么办?并非错误而是管理机制变更》很多朋友反馈,更新到Debian13后网络转发等功能异常,这并非BUG而是Debian13Trixie调整... 日前 Debian 13 Trixie 发布后已经有众多网友升级到新版本,只不过升级后发现某些功能存在异常,例如网络转

Python 基于http.server模块实现简单http服务的代码举例

《Python基于http.server模块实现简单http服务的代码举例》Pythonhttp.server模块通过继承BaseHTTPRequestHandler处理HTTP请求,使用Threa... 目录测试环境代码实现相关介绍模块简介类及相关函数简介参考链接测试环境win11专业版python

Python实战之SEO优化自动化工具开发指南

《Python实战之SEO优化自动化工具开发指南》在数字化营销时代,搜索引擎优化(SEO)已成为网站获取流量的重要手段,本文将带您使用Python开发一套完整的SEO自动化工具,需要的可以了解下... 目录前言项目概述技术栈选择核心模块实现1. 关键词研究模块2. 网站技术seo检测模块3. 内容优化分析模

基于Java开发一个极简版敏感词检测工具

《基于Java开发一个极简版敏感词检测工具》这篇文章主要为大家详细介绍了如何基于Java开发一个极简版敏感词检测工具,文中的示例代码简洁易懂,感兴趣的小伙伴可以跟随小编一起学习一下... 目录你是否还在为敏感词检测头疼一、极简版Java敏感词检测工具的3大核心优势1.1 优势1:DFA算法驱动,效率提升10

基于Java和FFmpeg实现视频压缩和剪辑功能

《基于Java和FFmpeg实现视频压缩和剪辑功能》在视频处理开发中,压缩和剪辑是常见的需求,本文将介绍如何使用Java结合FFmpeg实现视频压缩和剪辑功能,同时去除数据库操作,仅专注于视频处理,需... 目录引言1. 环境准备1.1 项目依赖1.2 安装 FFmpeg2. 视频压缩功能实现2.1 主要功