分类 C# 下的文章

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(o =>
    {
        o.LoginPath = "/user/login";
    });

app.UseRouting();
app.UseAuthentication();    //增加登录验证,注意顺序
app.UseAuthorization();

登录验证成功后:

var claims = new List<Claim>()
{
    new Claim(ClaimTypes.Name, userInfo.Nickname),
    new Claim(ClaimTypes.NameIdentifier, userInfo.ID.ToString()),
    new Claim("Phone", userInfo.Phone)
};
var claimnsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

//它会自动发送token给客户端。并生成cookies
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimnsIdentity), 
    new AuthenticationProperties
    {
        IsPersistent = true
    });

验证:

context.HttpContext.User.Identity.IsAuthenticated

取值:

string? Nickname = context.HttpContext.User.Identity.Name
string? uid = context.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value
string phone = context.HttpContext.User.FindFirst("Phone")?.Value ?? "18011112222";

有时为了让前端更方便的修改 cshtml 文件,又不想在前端电脑上安装开发环境,就想打包出来,view 还是像老版本的 mvc 一样独立怎么办呢,很简单3步搞定:

1、修改 .csproj 项目文件:

<PropertyGroup>
    <!--不打包视图文件-->
    <RazorCompileOnBuild>false</RazorCompileOnBuild>
    <RazorCompileOnPublish>false</RazorCompileOnPublish>
</PropertyGroup>

2、添加 nuget 包引用:Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation
3、修改 Program.cs:

builder.Services.AddRazorPages().AddRazorRuntimeCompilation();

需要在 Program.cs (or Startup.cs) 中增加:
builder.Services.AddControllers();

var app = builder.Build();

app.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");