我的代码在工作之前就可以使用,但是经过优化后,该代码无法正常工作,而且从昨天开始,我一直在试图找出问题所在... 问题是,成功登录后,我无法在_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!");
});
}
AccountController
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>
}
答案 0 :(得分:0)
我是.net core的新手,我不知道在启动课程中应用程序的顺序很重要。 一旦我移动了app.UseAuthentication();到“配置方法”的顶部,一切开始工作。对我来说这没有意义,但它解决了我的问题。