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

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

问题描述

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

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

获取错误:


HttpContext不能为空。

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身份验证。由于该应用程序的性质,即使该应用程序仍仅使用Windows Auth,我也添加了Core Identity进行角色管理。

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.

自从我迁移到Macbook进行开发以来,由于没有Windows Auth,因此我尝试使用已存在的Identity进行构建时自动登录以进行调试。适合,但出现上述错误。

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


推荐答案

对于 HttpContext ,它仅存在于http请求管道中。 Configure 方法中没有 HttpContext ,您需要在中间件期间引用代码。

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

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

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

注意:,您需要调用 app。 UseAuthentication(); ,订单已导入。

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天全站免登陆