【问题标题】:InvalidOperationException: Unable to resolve service for type'Microsoft.EntityFrameworkCore.DbContextOptions`1InvalidOperationException:无法解析类型“Microsoft.EntityFrameworkCore.DbContextOptions`1 的服务”
【发布时间】:2019-03-26 04:30:56
【问题描述】:

我需要使用 web api 创建登录,但是当我输入此 url https://localhost:44366/api/login 时显示此错误:

InvalidOperationException:尝试激活“IRI.DataLayer.Context.ApplicationDbContext”时,无法解析“Microsoft.EntityFrameworkCore.DbContextOptions`1[IRI.DataLayer.Context.ApplicationDbContext]”类型的服务。

然后输入网址https://localhost:44366/api/login/Authenticate 告诉我这个错误

找不到此本地主机页面 没有找到该网址的网页:https://localhost:44366/api/login/Authenticate HTTP 错误 404

有什么问题?我该如何解决这个问题?

我的代码 =>

登录控制器:

 [Route("api/[controller]")]
[ApiController]
public class LoginController : ControllerBase
{
    private readonly IApplicationUserManager _userManager;
    private readonly IApplicationSignInManager _signIn;
    private readonly IOptionsSnapshot<SiteSetting> _options;
    private readonly ILogger<LoginController> _logger;
    public LoginController(IApplicationUserManager userManager
        , IApplicationSignInManager signIn
        , IOptionsSnapshot<SiteSetting> options
        , ILogger<LoginController> logger)
    {
        _userManager = userManager;
        _userManager.CheckArgumentIsNull(nameof(_userManager));
        _options = options;
        _options.CheckArgumentIsNull(nameof(_options));
        _signIn = signIn;
        _signIn.CheckArgumentIsNull(nameof(_signIn));
        _logger = logger;
        _logger.CheckArgumentIsNull(nameof(_logger));

    }

    public async Task<IActionResult> Authenticate(LoginViewModel model, string returnUrl = null)
    {
        if (ModelState.IsValid)
        {
            var user = await _userManager.FindByNameAsync(model.username);
            if (user == null)
            {
                return BadRequest(Messages.IncorrectUsernamePassword);
            }
            if (!user.IsActive)
            {
                return BadRequest(Messages.NotActive);
            }
            if (_options.Value.EnableEmailConfirmation
                && await _userManager.IsEmailConfirmedAsync(user))
            {
                return BadRequest(Messages.EmailConfirmation);
            }
        }
        var result = await _signIn.PasswordSignInAsync(
                                model.username,
                                model.password,
                                model.rememberme,
                                lockoutOnFailure: true);
        if (result.Succeeded)
        {
            _logger.LogInformation(1, $"{model.username} logged in");
            return Ok(User);
        }
        if (result.RequiresTwoFactor)
        {
            //TODO Create Function for TowFactor 
        }
        if (result.IsNotAllowed)
        {
            return BadRequest(Messages.NotAllowed);
        }
        if (result.IsLockedOut)
        {
            _logger.LogWarning(2, $"{model.username} قفل شده‌است.");
            return BadRequest(Messages.IsLocked);
        }
        return BadRequest(Messages.IncorrectUsernamePassword);
    }
}

}

启动:

        public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        services.AddCustomServices();
    }

添加自定义服务:

 public static IServiceCollection AddCustomServices(this IServiceCollection services)
    {
        services.AddScoped<IUnitOfWork, ApplicationDbContext>();
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddScoped<IPrincipal>(provider =>
            provider.GetService<IHttpContextAccessor>()?.HttpContext?.User ?? ClaimsPrincipal.Current);

        services.AddScoped<IApplicationSignInManager, ApplicationSignInManager>();
        services.AddScoped<SignInManager<User>, ApplicationSignInManager>();

        services.AddScoped<IApplicationUserManager, ApplicationUserManager>();
        services.AddScoped<UserManager<User>, ApplicationUserManager>();

        services.AddScoped<IApplicationUserStore, ApplicationUserStore>();
        services.AddScoped<UserStore<User, Role, ApplicationDbContext, int, UserClaim, UserRole, UserLogin, UserToken, RoleClaim>, ApplicationUserStore>();

        return services;
    }

【问题讨论】:

    标签: asp.net asp.net-core asp.net-core-2.0 asp.net-core-webapi asp.net-core-2.1


    【解决方案1】:

    您尚未在应用程序中配置 DbContext。

    将 IdentityDbContext 添加到您的应用程序:

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbContextOptions options)
            : base(options)
        {
        }
    }
    

    然后在 ConfigureServices 中注册:

    services.AddDbContextPool<ApplicationDbContext>(opt => opt.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));
    

    还有定义 ConnectionStrings 的 appSettings.json :

    {
      "ConnectionStrings": {
        "DefaultConnection": "Server=Server-Name; Database=DBName; Trusted_Connection=True; MultipleActiveResultSets=True;"
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-08-07
      • 1970-01-01
      • 2016-09-19
      • 2021-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多