You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VS2022中ASP.NET Web Application(.NET Framework)无法找到Identity脚手架选项怎么办?

解决ASP.NET Web Application(.NET Framework)中无法找到Identity脚手架的问题

一、先安装Identity相关NuGet包

ASP.NET Web Application(.NET Framework)的Identity脚手架不会默认显示,必须先安装对应依赖包:

  • 右键项目 → 选择「管理NuGet程序包」
  • 搜索并安装以下包:
    • Microsoft.AspNet.Identity.Core
    • Microsoft.AspNet.Identity.EntityFramework
    • Microsoft.AspNet.Identity.Owin
    • Microsoft.Owin.Host.SystemWeb
  • 安装完成后重启Visual Studio,再打开「添加>新建脚手架项」,Identity选项应该会出现。

二、手动搭建Identity功能(脚手架仍不显示时)

如果安装包后还是找不到脚手架,可以手动实现核心功能:

1. 创建Identity模型类

添加IdentityModels.cs文件,定义自定义用户、角色和数据库上下文:

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Data.Entity;

public class ApplicationUser : IdentityUser
{
    // 可添加自定义属性,如真实姓名、生日等
}

public class ApplicationRole : IdentityRole
{
    public ApplicationRole() : base() { }
    public ApplicationRole(string name) : base(name) { }
    // 可添加自定义角色属性
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        // 可选:自定义数据库表名,比如将AspNetUsers改为Users
        modelBuilder.Entity<ApplicationUser>().ToTable("Users");
        modelBuilder.Entity<IdentityRole>().ToTable("Roles");
        modelBuilder.Entity<IdentityUserRole>().ToTable("UserRoles");
        modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaims");
        modelBuilder.Entity<IdentityUserLogin>().ToTable("UserLogins");
    }
}

2. 配置OWIN启动项

在App_Start文件夹添加Startup.Auth.cs:

using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;

[assembly: OwinStartupAttribute(typeof(YourProjectNamespace.Startup))]
namespace YourProjectNamespace
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }

        public void ConfigureAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.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))
                }
            });
        }
    }
}

同时添加用户管理器和角色管理器类(可放在IdentityModels.cs或单独文件):

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;

public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    {
    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
    {
        var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
        manager.UserValidator = new UserValidator<ApplicationUser>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = true,
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = true,
        };

        var dataProtectionProvider = options.DataProtectionProvider;
        if (dataProtectionProvider != null)
        {
            manager.UserTokenProvider =
                new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
        }
        return manager;
    }
}

public class ApplicationRoleManager : RoleManager<ApplicationRole>
{
    public ApplicationRoleManager(IRoleStore<ApplicationRole, string> roleStore)
        : base(roleStore)
    {
    }

    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
    {
        return new ApplicationRoleManager(new RoleStore<ApplicationRole>(context.Get<ApplicationDbContext>()));
    }
}

3. 实现Account控制器

手动创建AccountController,处理登录、注册和角色管理逻辑:

using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;

public class AccountController : Controller
{
    private ApplicationUserManager _userManager;
    private ApplicationRoleManager _roleManager;

    public ApplicationUserManager UserManager
    {
        get => _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        private set => _userManager = value;
    }

    public ApplicationRoleManager RoleManager
    {
        get => _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
        private set => _roleManager = value;
    }

    // GET: Account/Login
    public ActionResult Login(string returnUrl)
    {
        ViewBag.ReturnUrl = returnUrl;
        return View();
    }

    // POST: Account/Login
    [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);
        }
        ModelState.AddModelError("", "无效的用户名或密码");
        return View(model);
    }

    // GET: Account/Register
    public ActionResult Register() => View();

    // POST: Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (!ModelState.IsValid) return View(model);

        var user = new ApplicationUser { UserName = model.UserName, Email = model.Email };
        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            await UserManager.AddToRoleAsync(user.Id, "User");
            await SignInAsync(user, false);
            return RedirectToAction("Index", "Home");
        }
        AddErrors(result);
        return View(model);
    }

    // 创建管理员角色示例
    public async Task<ActionResult> CreateAdminRole()
    {
        if (!await RoleManager.RoleExistsAsync("Admin"))
        {
            await RoleManager.CreateAsync(new ApplicationRole("Admin"));
        }
        return RedirectToAction("Index", "Home");
    }

    // 辅助方法
    private async Task SignInAsync(ApplicationUser user, bool isPersistent)
    {
        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
        var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
        AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, identity);
    }

    private IAuthenticationManager AuthenticationManager => HttpContext.GetOwinContext().Authentication;

    private void AddErrors(IdentityResult result)
    {
        foreach (var error in result.Errors)
        {
            ModelState.AddModelError("", error);
        }
    }

    private ActionResult RedirectToLocal(string returnUrl)
    {
        return Url.IsLocalUrl(returnUrl) ? Redirect(returnUrl) : RedirectToAction("Index", "Home");
    }
}

添加对应的ViewModel类:

using System.ComponentModel.DataAnnotations;

public class LoginViewModel
{
    [Required]
    [Display(Name = "用户名")]
    public string UserName { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "密码")]
    public string Password { get; set; }

    [Display(Name = "记住我")]
    public bool RememberMe { get; set; }
}

public class RegisterViewModel
{
    [Required]
    [Display(Name = "用户名")]
    public string UserName { get; set; }

    [Required]
    [EmailAddress]
    [Display(Name = "邮箱")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "{0} 至少需要 {2} 个字符", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "密码")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "确认密码")]
    [Compare("Password", ErrorMessage = "密码与确认密码不匹配")]
    public string ConfirmPassword { get; set; }
}

4. 创建视图

为Account控制器的Login、Register等方法创建Razor视图,实现前端表单界面。

三、配置数据库连接字符串

确保Web.config中的DefaultConnection指向正确的数据库:

<connectionStrings>
  <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-YourProjectName.mdf;Initial Catalog=aspnet-YourProjectName;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

四、初始化角色和管理员用户

在Global.asax的Application_Start方法中添加初始化代码:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    InitializeIdentity();
}

private void InitializeIdentity()
{
    var context = new ApplicationDbContext();
    var roleManager = new ApplicationRoleManager(new RoleStore<ApplicationRole>(context));
    var userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(context));

    // 创建Admin角色
    if (!roleManager.RoleExists("Admin"))
    {
        roleManager.Create(new ApplicationRole("Admin"));
    }

    // 创建管理员用户
    var admin = userManager.FindByName("admin");
    if (admin == null)
    {
        var user = new ApplicationUser { UserName = "admin", Email = "admin@example.com" };
        var result = userManager.Create(user, "Admin@123");
        if (result.Succeeded)
        {
            userManager.AddToRole(user.Id, "Admin");
        }
    }
}

内容的提问来源于stack exchange,提问作者Volkan Akgül

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 04:00:05