简体   繁体   English

无法解析“Microsoft.AspNetCore.Identity.UserManager”类型的服务

[英]Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager

I am a beginner to learn asp core API,I got an error when using a program postman class startup我是初学者学习asp内核API,使用程序postman class启动时出错

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using project7.Models;

namespace project7
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddDbContext<ApplicationDb>(option => option.UseSqlServer(Configuration.GetConnectionString("MyConnection")));
            //  services.AddDefaultIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<ApplicationDb>();
           // _ = (services.AddIdentity<IdentityUser, IdentityRole>()..AddEntityFrameworkStores<ApplicationDb>().AddDefaultTokenProviders());

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

class AccountController class AccountController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using project7.Models;
using project7.ModelViews;

namespace project7.Controllers
{
    [Route("[controller]")]
    [ApiController]
    public class AccountController : ControllerBase
    {
        private readonly ApplicationDb _db;
        private readonly UserManager<ApplicationUser> _manager;

        public AccountController(ApplicationDb db, UserManager<ApplicationUser> manger)
        {

            _db = db;

            _manager = manger;
        }
        [HttpPost]  
        [Route("Register")]
        public async Task<IActionResult> Register(ResgisterModel model)
        {
            if( model == null)
            {
                return NotFound();
            }
            if (ModelState.IsValid)
            {


                if (EmailExistes(model.Email))
                {
                    return BadRequest("Email is not avalibel");
                }
                var user = new ApplicationUser
                {
                    Email = model.Email,
                    UserName = model.Email,
                    PasswordHash = model.Password

                };

                var result = await _manager.CreateAsync(user);
                if( result.Succeeded)
                {
                    return StatusCode(StatusCodes.Status200OK);
                }
                else
                {
                   return BadRequest(result.Errors);
                }
            }
            return StatusCode(StatusCodes.Status400BadRequest);
        }


        private bool EmailExistes(string email)
        {
           return _db.Users.Any(x=>x.Email == email );
        }
    }
}

This class ApplicationDb此 class 应用数据库

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace project7.Models
{
    public class ApplicationDb : IdentityDbContext<ApplicationUser, ApplicationRole, string>
    {

        public ApplicationDb(DbContextOptions<ApplicationDb> option) : base(option)
        {


        }
    }
}


I tried to send a post to the link "https: // localhost: 44371 / Account / Register" from Postman.我尝试从 Postman 向链接“https://localhost:44371/Account/Register”发送帖子。 This message appeared to me.这条消息出现在我面前。

System.InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager`1[project7.Models.ApplicationUser]' while attempting to activate 'project7.Controllers.AccountController'.
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
   at lambda_method(Closure , IServiceProvider , Object[] )
   at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass4_0.<CreateActivator>b__0(ControllerContext controllerContext)
   at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass5_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

HEADERS
=======
Accept: */*
Accept-Encoding: gzip, deflate, br
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 71
Content-Type: application/json
Host: localhost:44371
User-Agent: PostmanRuntime/7.24.1
Postman-Token: 858f3f5f-aa63-47ac-bb8e-c62686d6a651

And I have the following code in the ApplicationUser class:我在 ApplicationUser class 中有以下代码:

using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace project7.Models
{
    public class ApplicationUser: IdentityUser 
    {
        public string Country { get; set; }
    }
}

And I have the following code in the ApplicationUser class:我在 ApplicationUser class 中有以下代码:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace project7.ModelViews
{
    public class ResgisterModel
    {
        [StringLength(256),Required]
        public string Email { get; set; }

        [StringLength(256), Required]
        public string UserName { get; set; }

        [Required]
        public string Password { get; set; }
    }
}

I saw after the previous solutions but it was not effective with the code我看到了之前的解决方案,但对代码无效

Mostly you missed your service registration in startup, register your service using AddDefaultIdentity大多数情况下,您在启动时错过了服务注册,请使用 AddDefaultIdentity 注册您的服务

services.AddDefaultIdentity<ApplicationUser>()
            .AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试激活“AuthController”时无法解析“Microsoft.AspNetCore.Identity.UserManager”类型的服务 - Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager` while attempting to activate 'AuthController' 尝试激活“ Controllers.AccountsController”时无法解析类型为“ Microsoft.AspNetCore.Identity.UserManager”的服务 - Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager hile attempting to activate 'Controllers.AccountsController' 尝试激活“AuthenticateController”时无法解析“Microsoft.AspNetCore.Identity.UserManager”类型的服务 - Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager` while attempting to activate 'AuthenticateController' 如何解决“无法解析类型为‘Microsoft.AspNetCore.Identity.UserManager’的服务”? - How to solve "Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager"? 尝试激活“Management.Controllers.RoleController”时无法解析“Microsoft.AspNetCore.Identity.UserManager”类型的服务 - Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager' while attempting to activate 'Management.Controllers.RoleController' 尝试激活“WebShop.Controllers.User.UserController”时无法解析“Microsoft.AspNetCore.Identity.UserManager”类型的服务 - Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager' while attempting to activate 'WebShop.Controllers.User.UserController' 没有注册“Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]”类型的服务 - No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' has been registered 没有为“Microsoft.AspNetCore.Identity.UserManager`1[testLogin.Areas.Identity.Data.testLoginUser]”类型注册服务 - No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[testLogin.Areas.Identity.Data.testLoginUser]' has been registered InvalidOperationException:无法解析范围服务&#39;Microsoft.AspNetCore.Identity.UserManager .NET Core 2.0 - InvalidOperationException: Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.UserManager .NET Core 2.0 无法从根提供程序解析作用域服务“Microsoft.AspNetCore.Identity.UserManager`1[IdentityServerSample.Models.ApplicationUser]” - Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.UserManager`1[IdentityServerSample.Models.ApplicationUser]' from root provider
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM