question

elseforty-4971 avatar image
0 Votes"
elseforty-4971 asked elseforty-4971 commented

SignInManager not working when injected to razor page

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)
         {
         }
     }
 }


dotnet-aspnet-core-razor
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

miwan2-msft avatar image
0 Votes"
miwan2-msft answered elseforty-4971 commented

Hi, @elseforty-4971,

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





· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thank you this works perfectly, i was missing UseAuthentication

0 Votes 0 ·