use*_*570 5 c# asp.net-core-mvc .net-core asp.net-core asp.net-core-identity
我正在尝试在我构建的 ASP.net core 2.1 应用程序上自动登录以进行调试。
得到错误:
HttpContext 不能为空。
下面的代码位于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);
}
Run Code Online (Sandbox Code Playgroud)
这是我不久前问到的关于 Mac 上的 Windows 身份验证的另一个问题的扩展。由于应用程序的性质,我添加了用于角色管理的核心标识,即使应用程序仍然只使用 Windows 身份验证。
由于我迁移到 Macbook 进行开发,因此我尝试使用现有的身份自动登录构建以进行调试,因为没有 Windows 身份验证,这是 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
Run Code Online (Sandbox Code Playgroud)
对于HttpContext,它只存在于 http 请求管道中。没有HttpContextinConfigure方法,需要在中间件中引用代码。
对于使用Identity,您需要使用app.UseAuthentication();.
按照以下步骤使用 签名Identity。
配置请求管道。
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?}");
});
Run Code Online (Sandbox Code Playgroud)
注意:需要调用app.UseAuthentication();,顺序是import。
DeveloperLogin
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);
}
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
2055 次 |
| 最近记录: |