c# mvc登录验证
时间: 2023-10-20 22:09:16 浏览: 50
在C# MVC中,可以通过使用ASP.NET Identity来实现登录验证。具体步骤如下:
1. 在Visual Studio中创建一个新的MVC项目。
2. 在NuGet包管理器中安装Microsoft.AspNet.Identity.Core和Microsoft.AspNet.Identity.EntityFramework。
3. 在Models文件夹中创建一个名为ApplicationUser.cs的类,该类继承自IdentityUser类。
4. 在DbContext类中添加以下代码以启用Identity:
```
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
```
5. 在Startup.cs文件中添加以下代码以配置Identity:
```
public void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
}
```
6. 在AccountController.cs文件中添加以下代码以处理登录:
```
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await UserManager.FindAsync(model.UserName, model.Password);
if (user != null)
{
await SignInAsync(user, model.RememberMe);
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("", "Invalid username or password.");
return View(model);
}
}
```
7. 在Views文件夹中创建一个名为Login.cshtml的视图,该视图包含登录表单。