.net-core - UserManager.GetUserName(User) 登录成功后返回NULL
问题描述
我的代码在优化之前可以工作,但在优化之后,代码不起作用,从昨天开始,我试图找出问题所在......问题是,成功登录后,我无法在我的 _Layout 页面中获取用户名。UserManager 不断返回 null。
**在我的启动中**
public void ConfigureServices(IServiceCollection services)
{
services.AddDefaultIdentity<AppUser>(config => { config.SignIn.RequireConfirmedEmail = true; }).AddEntityFrameworkStores<AppIdentityDbContext>();
...........
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSession();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseStaticFiles();
app.UseHttpsRedirection();
app.UseMvcWithDefaultRoute();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
帐户控制器
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
await signInManager.SignOutAsync();
AppUser user = await userManager.FindByEmailAsync(model.Email);
if (user != null)
{
await signInManager.SignOutAsync();
var result = await signInManager.PasswordSignInAsync(user, model.Password, false, false);
if (result.Succeeded){ return Redirect("/Home");}
}
在帐户控制器中,用户成功登录,我调用了主页索引页面。在我的 _Layout 中,我想在导航栏中显示用户名。
_Layout.cshtml
@using Microsoft.AspNetCore.Identity
@inject SignInManager<AppUser> SignInManager
@inject UserManager<AppUser> UserManager
@if (UserManager.GetUserName(User) == null)
{
<a class="btn btn-warning"
asp-action="Login" asp-controller="Account">Log In</a>
}
else
{
<a class="btn btn-danger"
asp-action="Logout" asp-controller="Account">Log Out(@UserManager.GetUserName(User))</a>
}
解决方案
我是 .net 核心的新手,在启动课程中我不知道应用程序的顺序很重要。一旦我移动了 app.UseAuthentication(); 到配置方法的顶部,一切都开始工作了。这对我来说没有意义,但它解决了我的问题。
推荐阅读
- java - 当我创建另一个子弹对象时,如何连续移动这些“子弹”?
- python - 如何在 Django 中获取当前和本地日期和时间?
- node.js - nodejs AES/GCM/NoPadding 加密
- python - 如何在python中基于字符串中的子字符串应用条件函数?
- java - 使用 StringBuilder 将句子中第一个单词的第一个字母大写
- aem - Adobe AEM:创作期间未加载 Marketo 表单列表
- node.js - tsc 在生产构建期间未注册路径别名
- python - 在 python 中要求客户注册时,如何防止文本文件中的重复
- android - 如何使用 adb 更改 Android TV 画面设置?
- c# - 如何将不同类型的参数传递给.Net 5 web Api