首页 > 解决方案 > 为什么 userManager.GetUserName(User) 为空?

问题描述

我正在使用 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(User) 的位置:

登录成功:

名称为空:

标签: asp.netauthenticationasp.net-identity

解决方案


根据文档,GetUserName 将返回 Name 声明值(如果存在),否则返回 null。因此,您的 signmanager 身份上没有价值声明名称的答案。

首先尝试使用GetUserAsync()方法。并调试上面的内容。如果它为空,那么您的登录过程有问题。


推荐阅读