HttpContext.User является нулевым внутри контроллера в Asp. net core MVC 3.1 - PullRequest
0 голосов
/ 23 апреля 2020

В моем приложении я выполняю вход с помощью Claim и Использую аутентификацию cook ie без ASP. NET Идентификатор ядра

Для этого при входе в систему используйте следующий код: как описано здесь

var claims = new List<Claim>();

            foreach (var customclaim in customclaims)
            {
                claims.Add(new Claim(customclaim.Type, customclaim.Value));
            }

            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);


            var authProperties = new AuthenticationProperties
            {
                //AllowRefresh = true,
                //ExpiresUtc = DateTimeOffset.Now.AddDays(1),
                //IsPersistent = true,
            };



            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);

            return new RedirectResult("~/home");

и настройте Startup.cs, как показано ниже

public void ConfigureServices(IServiceCollection services)
        {


             services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
          .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
          {            


              options.LoginPath = new PathString("/");
              options.LogoutPath = new PathString("/Account/Logout");
              options.AccessDeniedPath = options.LoginPath;            
          });


            services.AddControllersWithViews(option =>
            {

            }) ;

            services.AddMvc();

        }


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();

            app.UseAuthorization();



            app.UseEndpoints(endpoints =>
            {
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute(
                        name: "arearoute",
                        pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");

                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Login}/{action=Index}/{id?}");
                });
            });
        }

, но после входа в HomeController Пользователь объект имеет значение null и через исключение NULL.

enter image description here

Как получить доступ к Пользователь из класса контроллера?

Спасибо

1 Ответ

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