下面是一个示例的解决方法,展示了如何创建一个ASP.NET Core个人用户认证登录/注册页面。
创建一个新的ASP.NET Core Web应用程序项目。
在Startup.cs文件中,添加所需的NuGet包:
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores();
services.Configure(options =>
{
options.LoginPath = "/Account/Login";
options.LogoutPath = "/Account/Logout";
options.AccessDeniedPath = "/Account/AccessDenied";
});
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
public class AccountController : Controller
{
private readonly SignInManager _signInManager;
public AccountController(SignInManager signInManager)
{
_signInManager = signInManager;
}
[HttpGet]
public IActionResult Login(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
}
[HttpPost]
public async Task Login(string username, string password, string returnUrl = null)
{
var result = await _signInManager.PasswordSignInAsync(username, password, false, lockoutOnFailure: false);
if (result.Succeeded)
{
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View();
}
}
[HttpGet]
public async Task Logout()
{
await _signInManager.SignOutAsync();
return RedirectToAction("Index", "Home");
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
}
@model IdentityUser
这只是一个简单的示例,你可以根据自己的需求进行修改和扩展。