我尝试了几种方法来从控制器内部获取登录用户,但似乎无法正常工作。这是我尝试过的示例之一。我看到的大多数示例都与.NET Core 1.x有关。从.NET Core 2.1中的控制器内部获取用户的方式是否有所不同?遵循示例之后,我的用户对象不断为null。谢谢! :)
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?}");
});
}
}
答案 0 :(得分:1)
您可以在ASP.Net Core操作方法中使用基本的Controller类IClaimsPrincipal User属性,而不是传统的httpcontext,前提是在Controller Constructor中初始化了UserManager并登录了User。如下所示
var user = await _userManager.GetUserAsync(this.User);
对于无记名令牌,请按名称获取登录用户。如下所示:
//Get userId
var userId = this.User.FindFirst(ClaimTypes.NameIdentifier).Value;
var user = await _userManager.FindByNameAsync(userName);