在SignInManager.PasswordSignInAsync上没有为此DbContext配置数据库提供程序

Bea*_*ore 45 c# entity-framework asp.net-identity-3 asp.net-core

.Net Core 1.0.0 - SDK Preview 2(x64)

.Net Core 1.0.0 - VS"15"预览版2(x64)

.Net Core 1.0.0 - 运行时(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);
    }
Run Code Online (Sandbox Code Playgroud)

它会出现以下错误消息:

InvalidOperationException:尚未为此DbContext配置任何数据库提供程序.可以通过覆盖DbContext.OnConfiguring方法或在应用程序服务提供程序上使用AddDbContext来配置提供程序.如果使用AddDbContext,那么还要确保您的DbContext类型在其构造函数中接受DbContextOptions对象,并将其传递给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?}");
        });
    }
Run Code Online (Sandbox Code Playgroud)

这是上下文:

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);
    }
Run Code Online (Sandbox Code Playgroud)

ade*_*lin 60

如果使用AddDbContext,那么还要确保您的DbContext类型在其构造函数中接受DbContextOptions对象,并将其传递给DbContext的基础构造函数.

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

    public LogManagerContext(DbContextOptions options) : base(options)
    {
    }
Run Code Online (Sandbox Code Playgroud)

编辑评论

如果您未IHttpContextAccessor明确注册,请使用以下代码:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); 
Run Code Online (Sandbox Code Playgroud)


Moh*_*ori 32

我可以通过在DConContextOptionsBuilder中添加连接字符串来覆盖MyContext中的Configuration来解决它:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
               .SetBasePath(Directory.GetCurrentDirectory())
               .AddJsonFile("appsettings.json")
               .Build();
            var connectionString = configuration.GetConnectionString("DbCoreConnectionString");
            optionsBuilder.UseSqlServer(connectionString);
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 如果缺少“SetBasePath”或“AddJsonFile”,请安装这些包:“Microsoft.Extensions.Configuration.FileExtensions”“Microsoft.Extensions.Configuration.Json” (9认同)
  • @alhpe说的很棒,不要在那里硬编码连接字符串,因为它将泄漏安全问题。可能您已经提到了替代解决方案应该是什么。 (5认同)
  • 请不要在OnConfiguring上硬编码连接字符串。这会泄漏安全问题 (3认同)

Oza*_*RAM 28

这是我找到的解决方案。

https://github.com/aspnet/EntityFramework.Docs/blob/master/entity-framework/core/miscellaneous/configuring-dbcontext.md

通过 AddDbContext 配置 DBContext

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<BloggingContext>(options => options.UseSqlite("Data Source=blog.db"));
}
Run Code Online (Sandbox Code Playgroud)

向您的 DBContext 类添加新的构造函数

public class BloggingContext : DbContext
{
    public BloggingContext(DbContextOptions<BloggingContext> options)
      :base(options)
    { }

    public DbSet<Blog> Blogs { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

将上下文注入您的控制器

public class MyController
{
    private readonly BloggingContext _context;

    public MyController(BloggingContext context)
    {
      _context = context;
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢 Ozan,你是我找到的第一个提到将上下文注入控制器的人。祝你有美好的一天! (6认同)

Chi*_*ils 28

我知道这已经很旧了,但这个答案仍然适用于较新的核心版本。

如果您的实现偶然DbContext位于与启动项目不同的项目中,并且您运行ef migrations,您将看到此错误,因为该命令将无法调用应用程序的启动代码,从而使您的数据库提供程序没有配置。要解决这个问题,你必须让他们ef migrations知道他们在哪里。

dotnet ef migrations add MyMigration [-p <relative path to DbContext project>, -s <relative path to startup project>]

-s都是-p可选的,默认为当前文件夹


Has*_*req 17

除了已接受的答案之外,如果有人即使在正确执行以下操作后仍然收到错误:

  • Startup.csservices.AddDbContext<ApplicationDbContext>(options => ... )
  • ApplicationDbContext.cspublic ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options){}

检查DbContext 类是否没有任何无参数公共构造函数(如果有,需要将其删除)。仅供参考,您可能会因某种原因添加无参数公共构造函数,即脚手架 DbContext。

详细信息(我在我的网站上写的文章):ASP.Net Core 故障排除


小智 6

尽管有带有 DbContextOptions 参数的构造函数,但我还是遇到了此错误。当我将解决方案启动从一个项目更改为多个项目时,出现了错误。检查解决方案->右键->属性->通用属性->启动项目中是否没有多个启动项目。

  • 这个解决方案解决了我的问题 (4认同)