在ASP.NET MVC中,身份验证默认控制器和视图可以通过以下步骤生成:
在Visual Studio中创建一个新的ASP.NET MVC项目。
在项目中打开“Tools”菜单,选择“NuGet包管理器”,然后选择“程序包管理器控制台”。
在控制台中运行以下命令来安装所需的包:
Install-Package Microsoft.AspNet.Identity.Samples -Version 2.2.1
以下是生成默认控制器和视图的代码示例:
在Global.asax.cs文件中,添加以下代码:
using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using MvcIdentitySample.Models;
namespace MvcIdentitySample
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
InitializeIdentity();
}
private void InitializeIdentity()
{
ApplicationDbContext context = new ApplicationDbContext();
IdentityManager manager = new IdentityManager(new UserManager(new UserStore(context)));
manager.CreateRole("Admin");
manager.CreateRole("User");
manager.AddUserToRole("admin@example.com", "Admin");
manager.AddUserToRole("user@example.com", "User");
}
}
}
在IdentityConfig.cs文件中,添加以下代码:
using System;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;
using MvcIdentitySample.Models;
namespace MvcIdentitySample
{
public class IdentityConfig
{
public void Configuration(IAppBuilder app)
{
app.CreatePerOwinContext(() => new ApplicationDbContext());
app.CreatePerOwinContext>((options, context) =>
new UserManager(new UserStore(context.Get())));
app.CreatePerOwinContext>((options, context) =>
new RoleManager(new RoleStore(context.Get())));
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
}
}
}
运行应用程序后,将会生成默认的Account控制器和视图。