c# - SignInManager.PasswordSignInAsync 上的“没有为此 DbContext 配置数据库提供程序”

标签 c# entity-framework asp.net-core asp.net-identity-3

.Net Core 1.0.0 - SDK Preview 2 (x64)

.Net Core 1.0.0 - VS "15" Preview 2 (x64)

.Net Core 1.0.0 - Runtime (x64)

因此,我们将 RC1 应用程序更新到上述最新版本。经过数小时的切换引用后,它正在运行。但是,在登录 (AccountController/Login) 时,我收到错误消息:

public class AccountController : BaseController
{
    public UserManager<ApplicationUser> UserManager { get; private set; }
    public SignInManager<ApplicationUser> SignInManager { get; private set; }
    private readonly IEmailSender EmailSender;

    public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, IEmailSender emailSender)
    {
        UserManager = userManager;
        SignInManager = signInManager;
        EmailSender = emailSender;
    }

    // GET: /Account/Login
    [HttpGet]
    [AllowAnonymous]
    public IActionResult Login(string returnUrl = null)
    {
        ViewBag.ReturnUrl = returnUrl;
        return View();
    }

    //
    // POST: /Account/Login
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(ViewModels.Account.LoginViewModel model, string returnUrl = null)
    {
        if (ModelState.IsValid)
        {
            // Errs this next line
            var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, false); // <-- ERRS HERE '.PasswordSignInAsync'
            if (result.Succeeded)
                return RedirectToLocal(returnUrl);

            ModelState.AddModelError("", "Invalid email or password.");
            return View(model);
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }
            

它爆炸并出现以下错误消息:

InvalidOperationException: No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.

这是 Startup.cs:

public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

        // Add EF services to the services container.
        services.AddEntityFrameworkSqlServer()
           .AddDbContext<LogManagerContext>(options =>
              options.UseSqlServer(Configuration["Data:DefaultConnection:Connectionstring"]));

        services.AddSingleton(c => Configuration);

        // Add Identity services to the services container.
        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<LogManagerContext>()
            .AddDefaultTokenProviders();
            
        
        // Add MVC services to the services container.
        services.AddMvc();

        services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();

        //Add all SignalR related services to IoC. - Signal R not ready yet - Chad
        //services.AddSignalR();

        //Add InMemoryCache
        services.AddMemoryCache();

        services.AddSession(options =>
        {
            options.IdleTimeout = System.TimeSpan.FromHours(1);
            options.CookieName = ".LogManager";
        });

        // Uncomment the following line to add Web API servcies which makes it easier to port Web API 2 controllers.
        // You need to add Microsoft.AspNet.Mvc.WebApiCompatShim package to project.json
        // services.AddWebApiConventions();
        // Register application services.
        services.AddTransient<IEmailSender, AuthMessageSender>();
        
    }

    // Configure is called after ConfigureServices is called.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseSession();

        // Configure the HTTP request pipeline.
        // Add the console logger.
        //loggerFactory.MinimumLevel = LogLevel.Information; - moved to appsettings.json -chad
        loggerFactory.AddConsole();
        loggerFactory.AddDebug();

        loggerFactory.AddNLog();

        // Add the following to the request pipeline only in development environment.
        if (env.IsDevelopment())
        {
            app.UseBrowserLink();
            app.UseDeveloperExceptionPage();
            //app.UseDatabaseErrorPage(DatabaseErrorPageOptions.ShowAll);
        }
        else
        {
            // Add Error handling middleware which catches all application specific errors and
            // sends the request to the following path or controller action.
            app.UseExceptionHandler("/Home/Error");
        }

        env.ConfigureNLog("NLog.config");

        // Add static files to the request pipeline.
        app.UseStaticFiles();

        // Add cookie-based authentication to the request pipeline.
        app.UseIdentity();

        //SignalR
        //app.UseSignalR();

        // Add MVC to the request pipeline.
        app.UseMvc(routes =>
        {
            routes.MapRoute(
             name: "default",
             template: "{controller}/{action}/{id?}",
             defaults: new { controller = "Home", action = "Index" }
             );

            // Uncomment the following line to add a route for porting Web API 2 controllers.
            // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
        });
    }

这是上下文:

public class ApplicationUser : IdentityUser
{
    // Add Custom Profile Fields
    public string Name { get; set; }
}

public class LogManagerContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<LogEvent> LogEvents { get; set; }
    public DbSet<Client> Clients { get; set; }
    public DbSet<LogEventsHistory> LogEventsHistory { get; set; }
    public DbSet<LogEventsLineHistory> LogEventsLineHistory { get; set; }
    public DbSet<LogRallyHistory> LogRallyHistory { get; set; }
    public DbSet<Flag> Flags { get; set; }
    protected override void OnModelCreating(ModelBuilder builder)
    {

        builder.Entity<LogEvent>().HasKey(x => x.LogId);
        builder.Entity<LogEvent>().ToTable("LogEvents");
        builder.Entity<Client>().HasKey(x => x.ClientId);
        builder.Entity<Client>().ToTable("Clients");
        builder.Entity<LogEventsHistory>().HasKey(x => x.HistoryId);
        builder.Entity<Flag>().HasKey(x => x.FlagId);
        builder.Entity<Flag>().ToTable("Flags");
        builder.Entity<LogRallyHistory>().HasKey(x => x.HistoryId);
        builder.Entity<LogEventsLineHistory>().HasKey(x => x.LineHistoryId);

        base.OnModelCreating(builder);
    }

最佳答案

If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.

错误消息说您的 DbContext(LogManagerContext ) 需要一个接受 DbContextOptions 的构造函数。但是我在你的 DbContext 中找不到这样的构造函数。因此,添加以下构造函数可能会解决您的问题。

public LogManagerContext(DbContextOptions options) : base(options)
{
}

编辑评论

如果您没有显式注册 IHttpContextAccessor,请使用以下代码:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); 

关于c# - SignInManager.PasswordSignInAsync 上的“没有为此 DbContext 配置数据库提供程序”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38338475/

相关文章:

c# - if else 在 asp.net 数据网格上填充数据源

c# - 如何使用 C# 从 mpg 视频创建缩略图?

c# - 为什么 double 精度在 C 和 C# 之间不同?

c# - 在 Where() 中使用 ToList().Last() 进行 Entity Framework 查询

c# - 单元测试 EF DbUpdateConcurrencyException 处理

asp.net - C# 类中的 SignalR Hub

c# - 绑定(bind)后台时"Must create DependencySource on same Thread as the DependencyObject."

entity-framework - 实体名称和实体集名称的区别

c# - 如何为 ASP.NET Core 中的单元/集成测试模拟 IFormFile?

c# - 在单个 ASP.NET Core 3.1 Web API 中管理两个 SPA;一个在根目录中,另一个在 "admin"路由中