Authe Token Beh - Как получить значение SignIn User в контроллере ASP.NET Core 2.1 - PullRequest
0 голосов
/ 14 января 2019

Я пробовал несколько способов получить зарегистрированного пользователя изнутри контроллера, но, похоже, он не работает. Вот один из примеров, которые я попробовал. Большинство примеров, которые я видел, были связаны с .NET Core 1.x. Есть ли разница в способе получить пользователя изнутри контроллера в .NET Core 2.1? Следуя примерам, я постоянно получаю нулевое значение для своего пользовательского объекта. Спасибо! :)

var user = await _userManager.GetUserAsync(HttpContext.User);

Startup.cs

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    //For ASP.NET Identity Only | You can reuse this but replace dbname with your own database name
    private string GetRdsConnectionString()
    {
        string hostname = Configuration.GetValue<string>("RDS_HOSTNAME");
        string port = Configuration.GetValue<string>("RDS_PORT");
        string dbname = "ASPNETIdentityUser";
        string username = Configuration.GetValue<string>("RDS_USERNAME");
        string password = Configuration.GetValue<string>("RDS_PASSWORD");

        return $"Data Source={hostname},{port};Initial Catalog={dbname};User ID={username};Password={password};";
    }

    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.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        //Using RDS
        services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
        GetRdsConnectionString()));

        //This has been commented out and moved to Identity Hosting Startup
        //services.AddIdentity<IdentityUser, IdentityRole>()
        //    .AddEntityFrameworkStores<ApplicationDbContext>()
        //    .AddDefaultTokenProviders();

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
    .AddRazorPagesOptions(options =>
    {
        options.AllowAreas = true;
        options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
        options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
    });

        services.ConfigureApplicationCookie(options =>
        {
            options.LoginPath = $"/Identity/Account/Login";
            options.LogoutPath = $"/Identity/Account/Logout";
            options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
        });
    }

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

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseAuthentication();


        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

1 Ответ

0 голосов
/ 14 января 2019

Вместо традиционного httpcontext вы можете использовать базовый класс Controller IClaimsPrincipal Свойство User в ASP.Net. Основной метод действия при условии, что UserManager инициализируется в конструкторе контроллера, а пользователь входит в систему. Как ниже

var user = await _userManager.GetUserAsync(this.User);

В случае токена на предъявителя, получить имя пользователя для входа в систему по имени. Как ниже:

//Get userId
var userId = this.User.FindFirst(ClaimTypes.NameIdentifier).Value;
var user = await _userManager.FindByNameAsync(userName);
...