ASP.NET Core 6 (.NET 6) 快速开发简单登陆和登出功能加.netCore WebAPI入门

前端 0

1.什么是asp.net

ASP.NET(Active Server Page .NET)又称为ASP+,不仅仅是ASP的简单升级,而是微软公司推出的新一代脚本语言。ASP.NET基于.NET Framework的Web开发平台,不但吸收了ASP以前版本的最大优点并参照Java、VB语言的开发优势加入了许多新的特色,同时也修正了以前的ASP版本的运行错误。 [1-2]

ASP.NET具备开发网站应用程序的一切解决方案,包括验证、缓存、状态管理、调试和部署等全部功能。在代码撰写方面特色是将页面逻辑和业务逻辑分开,它分离程序代码与显示的内容,让丰富多彩的网页更容易撰写。同时使程序代码看起来更洁净、更简单。 [2-3]

世界级的工具支持


ASP.net构架是可以用Microsoft(R)公司最新的产品 Visual Studio.net开发环境进行开发,WYSIWYG(What You See Is What You Get所见即为所得)的编辑。这些仅是ASP.net强大化软件支持的一小部分。

  强大性和适应性

  因为ASP.net是基于通用语言的编译运行的程序,所以它的强大性和适应性,可以使它运行在Web应用软件开发者的几乎全部的平台上(笔者到现在为止只知道它只能用在Windows 2000 Server上)。通用语言的基本库,消息机制,数据接口的处理都能无缝的整合到ASP.net的Web应用中。ASP.net同时也是language-independent语言独立化的,所以,你可以选择一种最适合你的语言来编写你的程序,或者把你的程序用很多种语言来写,现在已经支持的有C#(C++和Java的结合体),VB,Jscript。将来,这样的多种程序语言协同工作的能力保护您现在的基于COM+开发的程序,能够完整的移植向ASP.net。

  简单性和易学性

  ASP.net是运行一些很平常的任务如表单的提交客户端的身份验证、分布系统和网站配置变得非常简单。例如ASP.net页面构架允许你建立你自己的用户分界面,使其不同于常见的VB-Like界面。另外,通用语言简化开发使把代码结合成软件简单的就像装配电脑。

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

2、添加引用 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();

一、WebAPI实现

1、新建项目,选择ASP.NET Core Web API,点击下一步

2、框架选择.NET6.0(一定要用这个版本,网上有很多教程都是基于3.0或5.0的教程,如果选错了,后面配置的复杂度会比较高,建议选6.0),不要勾选启用Docker

3、创建完成后,按 Ctrl+F5 运行应用。 Visual Studio 启动浏览器并导航到 https://localhost:<port>/api/values,其中 <port> 是随机选择的端口号。

如果出现询问是否应信任 IIS Express 证书的对话框,则选择“是”。 在接下来出现的“安全警告”对话框中,选择“是”。

代码运行起来后就会在浏览器打开如下所示界面,点击页面上的GET方法,可以在该界面对系统默认生产的方法进行测试

4、安装项目依赖;使用NuGet添加EF环境:

Microsoft.EntityFrameworkCore.SqlServer

Microsoft.EntityFrameworkCore.Tools

5、添加模型类;在“解决方案资源管理器”中,右键单击项目。 选择“添加” > “新建文件夹”。 将文件夹命名为“Models”。

右键单击“Models”文件夹,然后选择“添加” > “类”。 将类命名为 merchants,然后选择“添加”。

将模板代码替换为以下代码

namespace Renners.Models
{
public class merchants
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Start { get; set; }
    
    public string Desc { get; set; }
    
}

}

也许您对下面的内容还感兴趣: