为什么 userManager.GetUserName(User) 为空?

Why userManager.GetUserName(User) is null?

我正在使用 Fiddler 测试我的 WEB API,登录工作完美(我认为),但是 当我想取回登录的用户名时,它会返回 null。

签到方式:

[HttpPost("signIn")]
    public async Task<IActionResult> SignIn(SignInViewModel model)
    {
        if (ModelState.IsValid)
        {
            var signInResult = await signInManager.PasswordSignInAsync(model.user_name, model.password, false, false);
            if (signInResult.Succeeded)
            {
                return Ok(model.user_name);
            }
        }
        return BadRequest(ModelState);
    }

破解方法:

[HttpPost("addGrade")]
    public async Task<ActionResult<Grades>> AddGrade(Grades grade)
    {
        if (ModelState.IsValid)
        {
            var name = userManager.GetUserName(User);
            grade.manufacturer = name.ToString();
            db.Add(grade);

            await db.SaveChangesAsync();
            return CreatedAtAction("Get", new { id = grade.id_grades }, grade);
        }
        else
        {
            return BadRequest(ModelState);
        }
    }

我的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.AddAuthorization();
        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie();
        services.AddDbContext<DiaryDataContext>();
        //services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddMvc(x => x.Filters.Add(new AuthorizeFilter())).AddXmlSerializerFormatters()
               .AddXmlDataContractSerializerFormatters();


        services.AddControllersWithViews();

        services.AddIdentity<IdentityUser, IdentityRole>()
            .AddEntityFrameworkStores<DiaryDataContext>()
            .AddDefaultTokenProviders();

        services.ConfigureApplicationCookie(opt =>
        {
            opt.ExpireTimeSpan = new TimeSpan(0, 5, 30);
            opt.Events = new CookieAuthenticationEvents
            {
                OnRedirectToLogin = redirextContext =>
                {
                    redirextContext.HttpContext.Response.StatusCode = 401;
                    return Task.CompletedTask;
                },
                OnRedirectToAccessDenied = redirectContext =>
                {
                    redirectContext.HttpContext.Response.StatusCode = 401;
                    return Task.CompletedTask;
                }
            };
        });
        //services.ConfigureApplicationCookie(options =>
        //{
        //    options.Cookie.HttpOnly = true;
        //    options.Cookie.Expiration = TimeSpan.FromSeconds();
        //    options.SlidingExpiration = true;
        //});
        //services.Configure<IdentityOptions>(options =>
        //  options.ClaimsIdentity.UserIdClaimType = ClaimTypes.NameIdentifier);
        




    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseAuthentication();

        app.UseRouting();
        app.UseAuthorization();
        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.UseExceptionHandler(
            options =>
            {
                options.Run(async context =>
                {
                    context.Response.StatusCode = 500;
                    context.Response.ContentType = "application/json";
                    //var ex = context.Features.Get<IExceptionHandlerFeature>();
                    //if (ex != null)
                    //{
                    //    await context.Response.WriteAsync(ex.Error.Message);
                    //}
                });
            });
        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.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapRazorPages();
        });
        //app.UseEndpoints(endpoints =>
        //{
        //    endpoints.MapControllerRoute(
        //        name: "default",
        //        pattern: "{controller=Home}/{action=Index}/{id?}");
        //});
        var cookiePolicyOptions = new CookiePolicyOptions
        {
            MinimumSameSitePolicy = SameSiteMode.Strict,
        };
        app.UseCookiePolicy(cookiePolicyOptions);


    }
}

登录成功的图片(使用Fiddler)和我想使用的地方userManager.GetUserName(用户):

基于 documentation,GetUserName 将 returns 名称声明值(如果存在)否则 returns 为空。因此,答案是您的 signmanager 身份上没有价值声明名称。

先尝试使用GetUserAsync()方法。并调试上面的内容。如果为null,则说明您的登录过程有问题。