首页 > 解决方案 > 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-core

解决方案


我是 .net 核心的新手,在启动课程中我不知道应用程序的顺序很重要。一旦我移动了 app.UseAuthentication(); 到配置方法的顶部,一切都开始工作了。这对我来说没有意义,但它解决了我的问题。


推荐阅读