asp.net core mvc登入注册代码
时间: 2023-08-08 16:12:46 浏览: 118
下面是一个简单的 ASP.NET Core MVC 登录注册示例,包括使用 Identity 进行身份验证和管理用户的功能。
1. 首先,打开 Visual Studio 并创建一个新的 ASP.NET Core Web 应用程序。
2. 选择 ASP.NET Core Web 应用程序模板,并选择“Individual User Accounts”身份验证选项。
3. 在解决方案资源管理器中,右键单击项目并选择“管理 NuGet 程序包”。
4. 在 NuGet 程序包管理器中,搜索并安装以下包:Microsoft.AspNetCore.Identity.EntityFrameworkCore、Microsoft.EntityFrameworkCore.SqlServer 和 Microsoft.EntityFrameworkCore.Tools。
5. 打开 Startup.cs 文件,并在 ConfigureServices 方法中添加以下代码:
```csharp
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.Configure<IdentityOptions>(options =>
{
// Password settings
options.Password.RequireDigit = true;
options.Password.RequiredLength = 8;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = true;
options.Password.RequireLowercase = false;
// Lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
options.Lockout.MaxFailedAccessAttempts = 10;
options.Lockout.AllowedForNewUsers = true;
// User settings
options.User.RequireUniqueEmail = true;
});
```
这段代码将添加 Identity 服务,并配置一些身份验证选项。
6. 在 Startup.cs 文件的 Configure 方法中添加以下代码:
```csharp
app.UseAuthentication();
```
这将启用身份验证中间件。
7. 创建一个名为“AccountController”的新控制器,并添加以下代码:
```csharp
public class AccountController : Controller
{
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly UserManager<ApplicationUser> _userManager;
public AccountController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
[HttpGet]
public IActionResult Register()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser
{
UserName = model.Email,
Email = model.Email
};
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
return View(model);
}
[HttpGet]
public IActionResult Login()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync(
model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
return RedirectToAction("Index", "Home");
}
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
}
return View(model);
}
[HttpPost]
public async Task<IActionResult> Logout()
{
await _signInManager.SignOutAsync();
return RedirectToAction("Index", "Home");
}
}
```
这段代码将处理用户注册、登录和注销的逻辑。请注意,我们使用了一些视图模型,如 RegisterViewModel 和 LoginViewModel,这些模型将用于表单验证和数据绑定。
8. 创建一个名为“RegisterViewModel”的新模型,用于表单验证和数据绑定。以下是一个示例:
```csharp
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 8)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
```
9. 创建一个名为“LoginViewModel”的新模型,用于表单验证和数据绑定。以下是一个示例:
```csharp
public class LoginViewModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
```
10. 最后,创建视图文件以呈现注册和登录表单。例如,以下是一个简单的注册视图:
```html
@model RegisterViewModel
<h2>Register</h2>
<form asp-action="Register" method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Email"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Password"></label>
<input asp-for="Password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="ConfirmPassword"></label>
<input asp-for="ConfirmPassword" class="form-control" />
<span asp-validation-for="ConfirmPassword" class="text-danger"></span>
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
```
这只是一个简单的示例,你可以根据自己的需要对其进行修改。
阅读全文