我正在尝试使用 IdentityServer4 设置授权服务器。当我尝试运行一段代码来生成测试数据时,出现以下错误。下面是代码
private static void InitializeDbTestData(IApplicationBuilder app)
{
using (var scope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
scope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate();
scope.ServiceProvider.GetRequiredService<ConfigurationDbContext>().Database.Migrate();
scope.ServiceProvider.GetRequiredService<UserDbContext>().Database.Migrate();
var context = scope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
if (!context.Clients.Any())
{
foreach (var client in Clients.Get())
{
context.Clients.Add(client.ToEntity());
}
context.SaveChanges();
}
if (!context.Scopes.Any())
{
foreach (var clientSope in Scopes.Get())
{
context.Scopes.Add(clientSope.ToEntity());
}
context.SaveChanges();
}
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
if (!userManager.Users.Any())
{
foreach (var applicationUser in Users.Get())
{
foreach (var claim in applicationUser.UserClaims)
{
//ExtendedClaimsProvider.CreateClaim()
applicationUser.Claims.Add(new IdentityUserClaim<Guid>
{
UserId = applicationUser.Id,
ClaimType = claim.Type,
ClaimValue = claim.Value,
});
}
userManager.CreateAsync(applicationUser, "Password123!").Wait();
}
}
}
}
错误是在什么时候产生的
scope.ServiceProvider.GetRequiredService<UserDbContext>().Database.Migrate();
被执行。
下面是生成的错误
System.InvalidOperationException was unhandled by user code HResult=-2146233079 Message=The property 'ClaimsIdentity.BootstrapContext' could not be mapped, because it is of type 'object' which is not a supported primitive type or a valid entity type. Either explicitly map this property, or ignore it.
Source=Microsoft.EntityFrameworkCore StackTrace:在 Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnModelBuilt(InternalModelBuilder modelBuilder) 在 Microsoft.EntityFrameworkCore.Infrastructure 的 Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.PropertyMappingValidationConvention.Apply(InternalModelBuilder modelBuilder)。 System.Collections.Concurrent.ConcurrentDictionary 中的 ModelSource.CreateModel(DbContext 上下文,IConventionSetBuilder 约定SetBuilder,IModelValidator 验证器)2.GetOrAdd(TKey key, Func
2 valueFactory) 在 Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel() 在 Microsoft.EntityFrameworkCore.Internal.LazyRef`1.get_Value() 在 Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider) 在 Microsoft.Extensions。 DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) 在 Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) 在 Microsoft.EntityFrameworkCore.DbContext.get_Model() 在 Microsoft.EntityFrameworkCore.DbContext.SetTEntity 在 ReportBook。 C:\Users\Julius\Documents\Projects\School\Development\ReportBook\ReportBook.Auth\Startup 中的 Auth.Startup.InitializeDbTestData(IApplicationBuilder 应用程序)。c:\Users\Julius\Documents\Projects\School\Development\ReportBook\ReportBook.Auth\Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 的 c:line 166:line 233内部异常:
以下是我的启动课
public class Startup
{
private readonly IHostingEnvironment _environment;
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsEnvironment("Development"))
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
_environment = env;
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
var connectionString = Configuration["Data:UserAccConnection:ConnectionString"];
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
var cert = new X509Certificate2(Path.Combine(_environment.ContentRootPath, "reportbook.auth.pfx"), "");
services.AddCors();
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
services.AddDbContext<UserDbContext>(options =>
options.UseSqlServer(connectionString, b => b.MigrationsAssembly(migrationsAssembly)));
// Register the Identity services.
services.AddIdentity<ApplicationUser, UserRole>()
.AddEntityFrameworkStores<UserDbContext, Guid>()
.AddDefaultTokenProviders();
services.AddIdentityServer()
.AddOperationalStore(builder => builder.UseSqlServer(connectionString, options => options.MigrationsAssembly(migrationsAssembly)))
.AddConfigurationStore(builder => builder.UseSqlServer(connectionString, options => options.MigrationsAssembly(migrationsAssembly)))
.SetSigningCredential(cert)
.AddProfileService<IdentityWithAdditionalClaimsProfileService>();
services.AddTransient<IProfileService, IdentityWithAdditionalClaimsProfileService>();
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
//services.AddTransient<IDatabaseInitializer, DatabaseInitializer>();
}
private static void InitializeDbTestData(IApplicationBuilder app)
{
using (var scope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
scope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate();
scope.ServiceProvider.GetRequiredService<ConfigurationDbContext>().Database.Migrate();
scope.ServiceProvider.GetRequiredService<UserDbContext>().Database.Migrate();
var context = scope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
if (!context.Clients.Any())
{
foreach (var client in Clients.Get())
{
context.Clients.Add(client.ToEntity());
}
context.SaveChanges();
}
if (!context.Scopes.Any())
{
foreach (var clientSope in Scopes.Get())
{
context.Scopes.Add(clientSope.ToEntity());
}
context.SaveChanges();
}
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
if (!userManager.Users.Any())
{
foreach (var applicationUser in Users.Get())
{
foreach (var claim in applicationUser.UserClaims)
{
//ExtendedClaimsProvider.CreateClaim()
applicationUser.Claims.Add(new IdentityUserClaim<Guid>
{
UserId = applicationUser.Id,
ClaimType = claim.Type,
ClaimValue = claim.Value,
});
}
userManager.CreateAsync(applicationUser, "Password123!").Wait();
}
}
}
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
app.UseDeveloperExceptionPage();
app.UseStaticFiles();
app.UseCors(builder =>
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
app.UseExceptionHandler(
builder =>
{
builder.Run(
async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false);
}
});
});
app.UseCsp(options => options.DefaultSources(directive => directive.Self())
.ImageSources(directive => directive.Self()
.CustomSources("*"))
.ScriptSources(directive => directive.Self()
.UnsafeInline())
.StyleSources(directive => directive.Self()
.UnsafeInline()));
app.UseXContentTypeOptions();
app.UseXfo(options => options.Deny());
app.UseXXssProtection(options => options.EnabledWithBlockMode());
InitializeDbTestData(app);
app.UseIdentity();
app.UseIdentityServer();
app.UseMvcWithDefaultRoute();
app.UseMvc();
//databaseInitializer.Seed(app).GetAwaiter().GetResult();
}
}
我将不胜感激