如何给Windows服务托管的ASP.NET Core示例添加ASP.NET Core Identity?
Hey there! Adding ASP.NET Core Identity to your Windows Service-hosted app is totally achievable—here's a clear, step-by-step guide to help you implement it:
Step 1: Install Required NuGet Packages
First, add the necessary Identity and Entity Framework Core packages via NuGet Package Manager or the .NET CLI:
- For Identity and EF Core integration:
Install-Package Microsoft.AspNetCore.Identity.EntityFrameworkCore # Or using dotnet CLI: # dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore - For your database provider (example using SQL Server):
Install-Package Microsoft.EntityFrameworkCore.SqlServer # Or using dotnet CLI: # dotnet add package Microsoft.EntityFrameworkCore.SqlServer - If you want the default Identity UI (login/register pages):
Install-Package Microsoft.AspNetCore.Identity.UI # Or using dotnet CLI: # dotnet add package Microsoft.AspNetCore.Identity.UI
Step 2: Create Identity-Related Classes
Define your custom user class (extend IdentityUser for extra fields if needed) and a DbContext that inherits from IdentityDbContext:
// AppUser.cs public class AppUser : IdentityUser { // Add custom properties here if needed, e.g.: // public string FullName { get; set; } } // AppDbContext.cs public class AppDbContext : IdentityDbContext<AppUser> { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } }
Step 3: Configure Services in Program.cs
Update your Program.cs to register the DbContext, Identity services, and set up middleware. Since you're using a Windows Service, your host builder will include UseWindowsService()—here's how to integrate Identity:
var builder = Host.CreateDefaultBuilder(args) .UseWindowsService() .ConfigureWebHostDefaults(webBuilder => { webBuilder.ConfigureServices(services => { // Configure DbContext with your connection string services.AddDbContext<AppDbContext>(options => options.UseSqlServer( builder.Configuration.GetConnectionString("DefaultConnection"))); // Register Identity services services.AddIdentity<AppUser, IdentityRole>() .AddEntityFrameworkStores<AppDbContext>() .AddDefaultTokenProviders(); // If using default Identity UI: // services.AddDefaultIdentity<AppUser>(options => options.SignIn.RequireConfirmedAccount = true) // .AddEntityFrameworkStores<AppDbContext>(); // Add authorization services services.AddAuthorization(); }) .Configure(app => { app.UseHttpsRedirection(); app.UseRouting(); // Critical: Add authentication middleware BEFORE authorization app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); // If using Identity UI, map Razor Pages: // endpoints.MapRazorPages(); }); }); }); var host = builder.Build(); host.Run();
Step 4: Set Up the Connection String
Add your database connection string to appsettings.json:
{ "ConnectionStrings": { "DefaultConnection": "Server=YOUR_SERVER;Database=YOUR_DB_NAME;Trusted_Connection=True;MultipleActiveResultSets=true" } }
Step 5: Apply Database Migrations
Identity requires database tables to store user/role data. Run these EF Core commands to create and apply migrations:
- Create an initial migration:
Add-Migration InitialIdentitySetup # Or dotnet CLI: # dotnet ef migrations add InitialIdentitySetup - Update the database to create the tables:
Update-Database # Or dotnet CLI: # dotnet ef database update
Key Notes to Avoid Issues
- Service Account Permissions: Ensure the Windows Service's running account has read/write access to your database. If using Local System, you may need to grant permissions for that account on your SQL Server.
- Middleware Order: Always place
UseAuthentication()beforeUseAuthorization()—this ensures user identities are validated before checking authorization rules. - Identity UI Routes: If you're using the default UI, make sure to map Razor Pages in your endpoints so the login/register pages are accessible.
Give these steps a shot—if you hit specific snags (like database connection errors or unexpected behavior with authentication), feel free to share more details and I’ll help you work through them!
内容的提问来源于stack exchange,提问作者kofifus

