调试 ASP.Net Core 2.1 时自动登录 [英] Auto Login on debug ASP.Net Core 2.1

查看:21
本文介绍了调试 ASP.Net Core 2.1 时自动登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我构建的 ASP.net core 2.1 应用程序上自动登录以进行调试.

获取错误:

<块引用>

HttpContext 不能为空.

下面的代码位于 Startup.cs 文件中

//这个方法被运行时调用.使用此方法配置 HTTP 请求管道.公共无效配置(IApplicationBuilder 应用程序,IHostingEnvironment 环境,IServiceProvider ServiceProvider){如果 (env.IsDevelopment()){app.UseDeveloperExceptionPage();}别的{app.UseExceptionHandler("/Home/Error");app.UseHsts();}app.UseHttpsRedirection();app.UseStaticFiles();app.UseMvc(routes =>{路线.MapRoute(名称:默认",模板:{controller=Home}/{action=Index}/{id?}");});app.UseCookiePolicy();CreateRoles(ServiceProvider).Wait();如果 (env.IsDevelopment()){DeveloperLogin(ServiceProvider).Wait();}}私有异步任务 DeveloperLogin(IServiceProvider serviceProvider){var UserManager = serviceProvider.GetRequiredService>();var signInManager = serviceProvider.GetRequiredService>();var _user = await UserManager.FindByNameAsync("test@gmail.com");等待 signInManager.SignInAsync(_user, isPersistent: false);}

这是对我不久前问到的关于 Mac 上的 Windows 身份验证的另一个问题的扩展.由于应用程序的性质,我添加了用于角色管理的核心标识,即使应用程序仍然只使用 Windows 身份验证.

自从我迁移到 Macbook 进行开发后,我尝试使用现有的身份自动登录构建以进行调试,因为没有 Windows 身份验证,这是 DeveloperLogin 函数适合的地方,但我收到了上面提到的错误.

堆栈跟踪:

 System.AggregateException:发生一个或多个错误.(HttpContext 不能为空.)"--->System.Exception {System.InvalidOperationException}:HttpContext 不能为空."在 Microsoft.AspNetCore.Identity.SignInManager`1.get_Context()在 Microsoft.AspNetCore.Identity.SignInManager`1.SignInAsync(TUser user, AuthenticationProperties authenticationProperties, String authenticationMethod)在/Users/user/Documents/Repositories/myApp/myApp/Startup.cs:135 中的 myApp.Startup.DeveloperLogin(IServiceProvider serviceProvider)

解决方案

对于 HttpContext,它只存在于 http 请求管道中.Configure 方法中没有HttpContext,中间件需要参考代码.

要使用Identity,您需要使用app.UseAuthentication();.

按照以下步骤使用 Identity 签名.

  • 配置请求管道.

     app.UseAuthentication();如果 (env.IsDevelopment()){app.Use(async (context, next) =>{var user = context.User.Identity.Name;DeveloperLogin(context).Wait();等待下一个调用();});}app.UseMvc(routes =>{路线.MapRoute(名称:默认",模板:{controller=Home}/{action=Index}/{id?}");});

    注意:需要调用app.UseAuthentication();,顺序是import.

  • DeveloperLogin

     私有异步任务 DeveloperLogin(HttpContext httpContext){var UserManager = httpContext.RequestServices.GetRequiredService>();var signInManager = httpContext.RequestServices.GetRequiredService>();var _user = await UserManager.FindByNameAsync("Tom");等待 signInManager.SignInAsync(_user, isPersistent: false);}

I am trying to auto login for debugging purposes on an ASP.net core 2.1 application I've built.

Getting the Error :

HttpContext must not be null.

The code below sits in the Startup.cs file

    // 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);

    }

This is an extension of sorts on another question I asked a while back about Windows Authentication on a Mac. Because of the nature of the application I had added Core Identity for role management even though the application still only uses Windows Auth.

Since I migrated to a Macbook for development I'm trying to autologin on build for debugging using the already existing Identity since there is no Windows Auth which is where the DeveloperLogin function fits in but I get the error mentioned above.

StackTrace:

    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

解决方案

For HttpContext, it only exists during http request pipeline. There is no HttpContext in Configure method, you need to refer the code during middleware.

For using Identity, you need to use app.UseAuthentication();.

Follow steps below with sigin with Identity.

  • Configure request pipeline.

        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?}");
        });
    

    Note: you need to call app.UseAuthentication();, the order is 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);
    
    }
    

这篇关于调试 ASP.Net Core 2.1 时自动登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆