1

In my application I sign-in with Claim and Use cookie authentication without ASP.NET Core Identity

For that in login action use bellow code ,as describe here

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");

and configure Startup.cs like bellow

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?}");
                });
            });
        }

but after login in HomeController User object is null and through null exception.

enter image description here

How can I access User from Controller class?

Thanks

kuntal
  • 1,591
  • 2
  • 16
  • 36
  • 1
    Does this answer your question? [How to get HttpContext.Current in ASP.NET Core?](https://stackoverflow.com/questions/38571032/how-to-get-httpcontext-current-in-asp-net-core) – Wai Ha Lee Oct 12 '20 at 07:04

0 Answers0