我正在尝试在我构建的 ASP.net core 2.1 应用程序上自动登录以进行调试。
获取错误:
HttpContext must not be null.
下面的代码位于 Startup.cs 文件中
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider ServiceProvider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
app.UseCookiePolicy();
CreateRoles(ServiceProvider).Wait();
if (env.IsDevelopment())
{
DeveloperLogin(ServiceProvider).Wait();
}
}
private async Task DeveloperLogin(IServiceProvider serviceProvider){
var UserManager = serviceProvider.GetRequiredService<UserManager<User>>();
var signInManager = serviceProvider.GetRequiredService<SignInManager<User>>();
var _user = await UserManager.FindByNameAsync("test@gmail.com");
await signInManager.SignInAsync(_user, isPersistent: false);
}
这是对我不久前提出的另一个关于 Mac 上的 Windows 身份验证问题的扩展。由于应用程序的性质,我已经为角色管理添加了 Core Identity,即使该应用程序仍然只使用 Windows Auth。
自从我迁移到 Macbook 进行开发后,我尝试在构建时自动登录以使用已经存在的身份进行调试,因为没有 Windows Auth,这正是 DeveloperLogin 函数适用的地方,但我得到了上述错误。
堆栈跟踪:
System.AggregateException: "One or more errors occurred. (HttpContext must not be null.)"
---> System.Exception {System.InvalidOperationException}: "HttpContext must not be null."
at Microsoft.AspNetCore.Identity.SignInManager`1.get_Context()
at Microsoft.AspNetCore.Identity.SignInManager`1.SignInAsync(TUser user, AuthenticationProperties authenticationProperties, String authenticationMethod)
at myApp.Startup.DeveloperLogin(IServiceProvider serviceProvider) in /Users/user/Documents/Repositories/myApp/myApp/Startup.cs:135
最佳答案
对于HttpContext
,它只存在于http请求管道中。 Configure
方法中没有HttpContext
,需要在中间件中引用代码。
要使用Identity
,您需要使用app.UseAuthentication();
。
按照以下步骤使用带有 Identity
的 sigin。
配置请求管道。
app.UseAuthentication(); if (env.IsDevelopment()) { app.Use(async (context, next) => { var user = context.User.Identity.Name; DeveloperLogin(context).Wait(); await next.Invoke(); }); } app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); });
注意:需要调用
app.UseAuthentication();
,顺序为import。开发人员登录
private async Task DeveloperLogin(HttpContext httpContext) { var UserManager = httpContext.RequestServices.GetRequiredService<UserManager<IdentityUser>>(); var signInManager = httpContext.RequestServices.GetRequiredService<SignInManager<IdentityUser>>(); var _user = await UserManager.FindByNameAsync("Tom"); await signInManager.SignInAsync(_user, isPersistent: false); }
关于c# - 调试 ASP.Net Core 2.1 时自动登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53514318/