C# Razor .net6 用户登录
参考资料:https://www.cnblogs.com/pfm33/p/14725660.html
1、Program.cs 加入:
builder.Services.AddRazorPages(options =>
{
//设置访问路由层级/下的页面都需要经过验证。
options.Conventions.AuthorizeFolder("/");
//因为 _Login.cshtml 是登录页,所以可以匿名访问.
options.Conventions.AllowAnonymousToPage("/_Login");
//上面两行设置可以用下面的这行替换(链式调用)
//options.Conventions.AuthorizeFolder("/Pages").AllowAnonymousToPage("/Pages/_Login");
});
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(
options =>
{
options.LoginPath = new PathString("/_Login");
}
);
// ----------------
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
}
else
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseRouting();
//启用身份验证,加上这句才能生效,
//注意顺序,在 app.UseRouting(); 和 app.UseAuthorization();之间
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
2、增加登陆页面,Razor页面自带 .cs 文件
3、Login.cshtml 里面写入:
@page
@model AuthManagement.Pages.Auth.SigninModel
@{
ViewData["Title"] = "用户登录";
}
<form method="post">
账号:
密码:
</form>
3、Login.cshtml.cs 里面写入:
using ****.Model;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace *****.Pages
{
public class _LoginModel : PageModel
{
private readonly MySqlDbContext _context;
public _LoginModel(MySqlDbContext context)
{
_context = context;
}
public void OnGet()
{
}
public async Task OnPost()
{
string userAcc = Request.Form["acc"];
//接收页面传递过来的账号
string userPwd = Request.Form["pwd"];
//接收页面传递过来的密码
string rememberMe = Request.Form["rememberMe"];
if(string.IsNullOrWhiteSpace(userAcc) || string.IsNullOrWhiteSpace(userPwd))
{
Response.Redirect("/_Login");
}
bool isRemember = rememberMe == "1" ? true : false;
user u = _context.User.Single();
}
}
}