如何解决SignInManager.IsSignedInUser方法始终返回false
如果使用-app.useAuthentication()中间件,则if条件始终返回false
_Layout.cshtml
@if (signInManager.IsSignedIn(User))
{
<li class="nav-item">
<form method="post" asp-controller="account" asp-action="logout">
<button type="submit" style="width:auto"
class="nav-link btn btn-link py-0">
Logout @User.Identity.Name
</button>
</form>
</li>
}
else
{
<li class="nav-item">
<a class="nav-link" asp-controller="account" asp-action="register">
Register
</a>
</li>
<li class="nav-item">
<a class="nav-link" asp-controller="account" asp-action="login">
Login
</a>
</li>
}
Satrtup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EmployeeManagementPractice.Modals;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace EmployeeManagementPractice
{
public class Startup
{
private IConfiguration _config;
public Startup(IConfiguration config)
{
_config = config;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication();
services.AddIdentity<IdentityUser,IdentityRole>(options =>
{
options.Password.RequiredLength = 8;
}).AddEntityFrameworkStores<AppDbContext>();
services.AddDbContextPool<AppDbContext>(
options => options.UseSqlServer(_config.GetConnectionString("EmployeeDBConnection")));
services.AddMvc(action => action.EnableEndpointRouting = false);
services.AddScoped<IEmployeeRepository,SQLEmployeeRepository>();
}
// 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("/Error");
app.UseStatusCodePagesWithReExecute("/Error/{0}");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute("default","{controller=home}/{action=index}/{id?}");
});
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/",async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
}
}
}
每当我在调试模式下运行mvc文件时,即使在正确的登录ID和密码之后,signInManager.IsSignedIn(User)也会返回false
在控制器中,在“登录操作”中-如果(结果成功)返回true,请帮助某人,为什么signInManager.IsSignedIn(User)返回false。
public async Task<IActionResult> Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
var result = await signInManager.PasswordSignInAsync(model.Email,model.Password,model.RememberMe,false);
if (result.Succeeded)
{
return RedirectToAction("index","home");
}
ModelState.AddModelError("","Invalid Login Password");
}
return View();
}
解决方法
检查DbContext
和AddIdentity
的顺序。如果您没有使用任何JWT令牌,我认为您不需要services.AddAuthentication();
的配置,因此我已将其删除。并查看下面的代码,您已经丢失了几件事。
public void ConfigureServices(IServiceCollection services)
{
//Add this two configuration
services.AddControllersWithViews();
services.AddRazorPages();
///////////////////
services.AddDbContextPool<AppDbContext>(
options => options.UseSqlServer(_config.GetConnectionString("EmployeeDBConnection")));
services.AddIdentity<IdentityUser,IdentityRole>(options =>
{
options.Password.RequiredLength = 6;
}).AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();
services.AddMvc(action => action.EnableEndpointRouting = false);
services.AddScoped<IEmployeeRepository,SQLEmployeeRepository>();
}
然后在Configure
中更改以下内容:
// 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("/Error");
app.UseStatusCodePagesWithReExecute("/Error/{0}");
}
//and this thing are also needed
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
//you have not given the path to redirect after login,so u need to add this.
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
如果您使用过_Layout.cshtml
,请检查:
@using Microsoft.AspNetCore.Identity
@inject SignInManager<IdentityUser> SignInManager
@inject UserManager<IdentityUser> UserManager
似乎您在此处使用的所有配置都是基于dotnet core 2.2。 asp.net core 3.1有所不同。
有关更多信息,请访问链接:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。