SignInManager not working when injected to razor page

elseforty 21 Reputation points
2021-03-29T23:10:55.033+00:00

Hi,
i'm having troubles getting SignInManager injected in a razor page , the signInManager.IsSignedIn(User) is alway false even if i'm loged in ,
Startup.cs

    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.AddDbContext<ApplicationDBContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")
           ));

            services.AddIdentity<IdentityUser, IdentityRole>(options=>{
                options.Password.RequiredLength = 5;
                options.SignIn.RequireConfirmedAccount = false;
                options.SignIn.RequireConfirmedEmail = false;
                options.SignIn.RequireConfirmedPhoneNumber = false;

            })
           .AddEntityFrameworkStores<ApplicationDBContext>()
              .AddDefaultTokenProviders();

            services.AddControllersWithViews();

        }

        // 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();
            }
            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.UseRouting();

            app.UseAuthorization();

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

razor page

@using Microsoft.AspNetCore.Identity
@model ElseForty.ViewModels.UserLoginViewModel
@inject SignInManager<IdentityUser> signInManager


@if (signInManager.IsSignedIn(User))
{
    <p> connected </p>
}
else
{
    <p> disconnected </p>
}

Controller

 public class UserController : Controller
    {
        public readonly UserManager<IdentityUser> userManager;
        public readonly SignInManager<IdentityUser> signInManager;
        //  private readonly ApplicationDBContext db;
        public UserController(UserManager<IdentityUser> _userManager, SignInManager<IdentityUser> _signInManager)
        {
            //   db = _db;
            userManager = _userManager;
            signInManager = _signInManager;
        }

        [HttpGet]
        public IActionResult Login()
        {

            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Login(UserLoginViewModel loginModel)
        {
            if (ModelState.IsValid)
            {
                 var result = await signInManager.PasswordSignInAsync(loginModel.UserName, loginModel.Password, loginModel.RememberMe, false);

                if (result.Succeeded)
                {
                    ViewData["con"] = "success";
                    return View();
                             //  return RedirectToAction("Index", "Home");
                }
                else
                {
                    ViewData["con"] = "failure";

                    ModelState.AddModelError(string.Empty, "Invalid Email or Password?!");
                    return View();
                }
            }
            else
            {
                return View();
            }
        }
}

applicationDBContext

    public class ApplicationDBContext : IdentityDbContext
    {
        public ApplicationDBContext(DbContextOptions<ApplicationDBContext> options ) :base(options)
        {
        }
    }
}
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
2,603 questions
No comments
{count} votes

Accepted answer
  1. Michael Wang-MSFT 1,046 Reputation points
    2021-03-30T07:15:45.447+00:00

    Hi, @elseforty ,

    Identity is enabled by calling UseAuthentication. UseAuthentication adds authentication middleware to the request pipeline.

    public void Configure(IApplicationBuilder app, IWebHostEnvironment 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.UseRouting();  
    
             app.UseAuthentication();  
    
             app.UseAuthorization();  
      
             app.UseEndpoints(endpoints =>  
             {  
                 endpoints.MapControllerRoute(  
                     name: "default",  
                     pattern: "{controller=Home}/{action=Index}/{id?}");  
             });  
         }  
    

    app.UseAuthorization is included to ensure it's added in the correct order should the app add authorization. UseRouting, UseAuthentication, UseAuthorization, and UseEndpoints must be called in the order shown in the preceding code.

    More details of Configure Identity services

    ------
    If the answer doesn’t solve your issue, please provide more details of error that will help us track down what’s happening.
    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards,
    Michael Wang


0 additional answers

Sort by: Most helpful