Ошибка при создании формы регистрации с использованием UserManager и SignInManager в основном приложении ASP. NET - PullRequest
0 голосов
/ 19 февраля 2020

Я пытаюсь создать форму регистрации, используя UserManager и SignInManager, однако я застрял с ошибкой.

Произошло необработанное исключение при обработке запроса.

InvalidOperationException : Не удается разрешить службу для типа «Microsoft.AspNetCore.Identity.UserManager`1 [Microsoft.AspNetCore.Identity.IdentityUser]» при попытке активировать «ProjectApplicationX00140684.Controllers.AccountController».

Здесь мой AccountController:

namespace ProjectApplicationX00140684.Controllers
{
    public class AccountController : Controller
    {
        private readonly UserManager<IdentityUser> userManager;
        private readonly SignInManager<IdentityUser> signInManager;

        public AccountController(UserManager<IdentityUser> userManager,
            SignInManager<IdentityUser> signInManager)
        {
            this.userManager = userManager;
            this.signInManager = signInManager;
        }

        [HttpGet]
        public IActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Register(Register model)
        {
            if (ModelState.IsValid)
            {
                // Copy data from RegisterViewModel to IdentityUser
                var user = new IdentityUser
                {
                    UserName = model.Email,
                    Email = model.Email
                };

                // Store user data in AspNetUsers database table
                var result = await userManager.CreateAsync(user, model.Password);

                // If user is successfully created, sign-in the user using
                // SignInManager and redirect to index action of HomeController
                if (result.Succeeded)
                {
                    await signInManager.SignInAsync(user, isPersistent: false);
                    return RedirectToAction("index", "home");
                }

                // If there are any errors, add them to the ModelState object
                // which will be displayed by the validation summary tag helper
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            return View(model);
        }
    }
}

Вот мой Startup.cs

namespace ProjectApplicationX00140684
{
    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.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext<VehicleContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

Ответы [ 2 ]

1 голос
/ 19 февраля 2020

Необходимо настроить службы идентификации, службы добавляются в методе ConfigureServices:

services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(
        Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>()
    .AddDefaultUI(UIFramework.Bootstrap4)
    .AddEntityFrameworkStores<ApplicationDbContext>();

ApplicationDbContext.cs:

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

И добавить промежуточное ПО аутентификации в конвейер запросов:

app.UseAuthentication();

После этого вы можете применить миграции (Update-Database) для обновления базы данных. Более подробную информацию и образец кода см. В документе:

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-2.2&tabs=visual-studio

0 голосов
/ 23 февраля 2020

Я бы предложил вам использовать шаблон аутентификации, доступный при запуске нового проекта. Установите флажок проверки подлинности в мастере проекта, а затем выберите отдельную опцию в приложении.

Это отсортирует все настройки для вас и добавит частичное для состояния входа в систему.

Затем можно добавить класс модели, который наследуется от идентификатора, чтобы добавить собственные настраиваемые поля, если это необходимо.

Если вы используете SPA, например, angular или реагируете, существуют шаблоны, которые также включают в себя аутентификацию.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...