ASP.NET Web表单与.NET Core 2.2,ihttpcontextaccessor.httpcontext混合

发布于 2025-01-25 15:23:40 字数 3537 浏览 1 评论 0原文

我正在尝试使用.NET CORE 2.2依赖项注入和ASP.NET Core 2.2旧的ASP.NET Web表单应用中的身份,我正确设置了依赖性注入。当我使用UserManager创建一个用户名和密码时,核心身份也可以工作。

但是我的问题是SignManager,因为它需要Microsoft.aspnetcore.http.httpcontext实例,以便设置主体。

我的启动是:

    [assembly: OwinStartupAttribute(typeof(WebForms22.Startup))]
namespace WebForms22
{
    public partial class Startup {

        public static IServiceProvider Services { get; set; }        
        
        public void Configuration(IAppBuilder app) 
        {           
            var services = new ServiceCollection();
            //ConfigureAuth(app);
            ConfigureServices(services);
            Services = services.BuildServiceProvider();

        }

        public void ConfigureServices(IServiceCollection services)
        {           
            services.AddDbContext<IdentityContext>(options =>
               options.UseSqlServer(
                   @"Server=localhost;Database=WebForms22;Trusted_Connection=True;MultipleActiveResultSets=true;"), ServiceLifetime.Transient);

            services.AddIdentity<AppUser, IdentityRole>(opts =>
            {
                opts.User.RequireUniqueEmail = true;
                //opts.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyz";
                opts.Password.RequiredLength = 6;
                opts.Password.RequireNonAlphanumeric = false;
                opts.Password.RequireLowercase = false;
                opts.Password.RequireUppercase = false;
                opts.Password.RequireDigit = false;
                opts.ClaimsIdentity.UserIdClaimType = JwtRegisteredClaimNames.Sub; //commented      
                opts.Tokens.EmailConfirmationTokenProvider = "custom";
            }).AddEntityFrameworkStores<IdentityContext>().AddDefaultTokenProviders()
            .AddTokenProvider<DataProtectorTokenProvider<AppUser>>("custom");

            services.AddHttpContextAccessor();
            //services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddTransient<DAL.Business.Account>();
            services.AddTransient<DAL.Business.Admin>();
            services.AddTransient<DAL.Business.Home>();
        }
      
    }
}

这是login.aspx.cs中的登录方法:

protected async void LogIn(object sender, EventArgs e)
        {
            if (IsValid)
            {
                // Validate the user password
                var manager = Startup.Services.GetRequiredService<UserManager<AppUser>>(); 
                var signinManager = Startup.Services.GetRequiredService<SignInManager<AppUser>>();  

                AppUser user = await manager.FindByNameAsync(Email.Text);
                change to shouldLockout: true

                var context = Startup.Services.GetRequiredService<IHttpContextAccessor>().HttpContext;  //<< Here              
                signinManager.Context = context; // == null       

                Microsoft.AspNetCore.Identity.SignInResult result = 
                  await signinManager.PasswordSignInAsync(user, Password.Text, RememberMe.Checked, true);                       
                
                if (result.Succeeded)
                {...

但是当我想登录时我会遇到此错误:

system.invalidoperationException:'httpcontext不得不为null。'

我如何如何在签名期间设置ASP.NET Core HttpContext?

编辑:

instup.services.getRequiredService&lt; ihttpContextAccessor&gt;()。httpcontext;

总是无效的

I am trying to use .Net Core 2.2 Dependency Injection and Asp.Net Core 2.2 Identity in an old Asp.Net web forms app, I setup dependency injection correctly. The core Identity also works when I created a user name and password using UserManager.

But My problem is SignInManager, since it needs a Microsoft.AspNetCore.Http.HttpContext instance so that principals are set.

My startup is:

    [assembly: OwinStartupAttribute(typeof(WebForms22.Startup))]
namespace WebForms22
{
    public partial class Startup {

        public static IServiceProvider Services { get; set; }        
        
        public void Configuration(IAppBuilder app) 
        {           
            var services = new ServiceCollection();
            //ConfigureAuth(app);
            ConfigureServices(services);
            Services = services.BuildServiceProvider();

        }

        public void ConfigureServices(IServiceCollection services)
        {           
            services.AddDbContext<IdentityContext>(options =>
               options.UseSqlServer(
                   @"Server=localhost;Database=WebForms22;Trusted_Connection=True;MultipleActiveResultSets=true;"), ServiceLifetime.Transient);

            services.AddIdentity<AppUser, IdentityRole>(opts =>
            {
                opts.User.RequireUniqueEmail = true;
                //opts.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyz";
                opts.Password.RequiredLength = 6;
                opts.Password.RequireNonAlphanumeric = false;
                opts.Password.RequireLowercase = false;
                opts.Password.RequireUppercase = false;
                opts.Password.RequireDigit = false;
                opts.ClaimsIdentity.UserIdClaimType = JwtRegisteredClaimNames.Sub; //commented      
                opts.Tokens.EmailConfirmationTokenProvider = "custom";
            }).AddEntityFrameworkStores<IdentityContext>().AddDefaultTokenProviders()
            .AddTokenProvider<DataProtectorTokenProvider<AppUser>>("custom");

            services.AddHttpContextAccessor();
            //services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddTransient<DAL.Business.Account>();
            services.AddTransient<DAL.Business.Admin>();
            services.AddTransient<DAL.Business.Home>();
        }
      
    }
}

And this is the Login method in Login.aspx.cs:

protected async void LogIn(object sender, EventArgs e)
        {
            if (IsValid)
            {
                // Validate the user password
                var manager = Startup.Services.GetRequiredService<UserManager<AppUser>>(); 
                var signinManager = Startup.Services.GetRequiredService<SignInManager<AppUser>>();  

                AppUser user = await manager.FindByNameAsync(Email.Text);
                change to shouldLockout: true

                var context = Startup.Services.GetRequiredService<IHttpContextAccessor>().HttpContext;  //<< Here              
                signinManager.Context = context; // == null       

                Microsoft.AspNetCore.Identity.SignInResult result = 
                  await signinManager.PasswordSignInAsync(user, Password.Text, RememberMe.Checked, true);                       
                
                if (result.Succeeded)
                {...

But I get this error when I want to Login:

System.InvalidOperationException: 'HttpContext must not be null.'

How do I set Asp.Net core HttpContext during signin?

EDIT: HttpContext in

Startup.Services.GetRequiredService<IHttpContextAccessor>().HttpContext;

is always null

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文