c# - 调试 ASP.Net Core 2.1 时自动登录

标签 c# asp.net-core .net-core asp.net-core-mvc asp.net-core-identity

我正在尝试在我构建的 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/

相关文章:

c# - 如何防止 ASP.net core 中的默认 url 解码

ASP.Net Core razor 页面处理程序成为一条包罗万象的路线

c# - 每个表只允许一个标识列

c# - Marshal.AllocHGlobal VS Marshal.AllocCoTaskMem,Marshal.SizeOf VS sizeof()

c# - 如何强制隐藏字段的标签助手以小写形式呈现 bool 值

c# - 尝试激活 'Microsoft.AspNetCore.Identity.UserManager' 时无法解析类型 'WebShop.Controllers.User.UserController' 的服务

.net - 如何在 .NET Core 2 中打开 project.json

c# - 将 2 个 Autofac 容器合并为一个

c# - 从 Controller 传递模型中的 ICollection 时,Ajax 方法将不再起作用

c# - 在 Asp.net Core Web API 中返回 "JsonResult/IActionResult"或 "Task<SomeObject>"或仅返回 "SomeObject"有什么区别?