Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Asp.Net Core 2.2-无法解析类型为';的服务;。。。签名者'1[…应用程序用户]';_C#_Asp.net Core_Asp.net Core Identity - Fatal编程技术网

C# Asp.Net Core 2.2-无法解析类型为';的服务;。。。签名者'1[…应用程序用户]';

C# Asp.Net Core 2.2-无法解析类型为';的服务;。。。签名者'1[…应用程序用户]';,c#,asp.net-core,asp.net-core-identity,C#,Asp.net Core,Asp.net Core Identity,尝试使用razor登录页面登录时,出现以下错误: 无法解析类型的服务 'DAL.Models.\u Auth.SignInHelper'1[DAL.Models.\u Auth.ApplicationUser]' 试图激活时 “AuthTest.Areas.Identity.Pages.Account.LoginModel” 这是我的签名助手课程: public class SignInHelper<T> where T : ApplicationUser { private

尝试使用razor登录页面登录时,出现以下错误:

无法解析类型的服务 'DAL.Models.\u Auth.SignInHelper'1[DAL.Models.\u Auth.ApplicationUser]' 试图激活时 “AuthTest.Areas.Identity.Pages.Account.LoginModel”

这是我的签名助手课程:

public class SignInHelper<T> where T : ApplicationUser
{
    private readonly SignInManager<T> _signInManager;

    public SignInHelper(SignInManager<T> signInManager)
    {
        _signInManager = signInManager;
    }

    public async Task SignInUserAsync(T user, bool isPersistent, IEnumerable<Claim> customClaims)
    {
        var claimsPrincipal = await _signInManager.CreateUserPrincipalAsync(user);
        if (customClaims != null && claimsPrincipal?.Identity is ClaimsIdentity claimsIdentity)
        {
            claimsIdentity.AddClaims(customClaims);
        }
        await _signInManager.Context.SignInAsync(IdentityConstants.ApplicationScheme,
            claimsPrincipal,
            new AuthenticationProperties { IsPersistent = isPersistent });
    }
}
公共类签名器,其中T:ApplicationUser
{
专用只读签名管理器\u签名管理器;
公共签名管理员(签名管理员签名管理员)
{
_signInManager=signInManager;
}
公共异步任务SignInUserAsync(T用户、bool ispersist、IEnumerable自定义声明)
{
var claimsPrincipal=wait _signInManager.createUserPrincipalSync(用户);
if(customClaims!=null&&claimsPrincipal?。标识为ClaimsIdentity ClaimsIdentity)
{
索赔实体。添加索赔(客户索赔);
}
wait_signInManager.Context.SignInAsync(IdentityConstants.ApplicationScheme,
索赔精神,
新的身份验证属性{IsPersistent=IsPersistent});
}
}
我的ApplicationUser类:

public class ApplicationUser : IdentityUser<Guid>
{
    public string FullName { get; set; }

    public virtual ICollection<ApplicationUserRole> UserRoles { get; set; }

    public virtual ICollection<IdentityUserClaim<Guid>> Claims { get; set; }

    public virtual ICollection<IdentityUserLogin<Guid>> Logins { get; set; }

    public virtual ICollection<IdentityUserToken<Guid>> Tokens { get; set; }


}
公共类应用程序用户:IdentityUser
{
公共字符串全名{get;set;}
公共虚拟ICollection用户角色{get;set;}
公共虚拟ICollection声明{get;set;}
公共虚拟ICollection登录名{get;set;}
公共虚拟ICollection令牌{get;set;}
}
和我的登录页面模型:

[AllowAnonymous]
public class LoginModel : PageModel
{
    private readonly MyDbContext _context;
    private readonly SignInHelper<ApplicationUser> _signInHelper;
    private readonly SignInManager<ApplicationUser> _signInManager;
    private readonly ILogger<LoginModel> _logger;

    public LoginModel(MyDbContext context,
        SignInManager<ApplicationUser> signInManager,
        SignInHelper<ApplicationUser> signInHelper,
        ILogger<LoginModel> logger)
    {
        _context = context;
        _signInHelper = signInHelper;
        _signInManager = signInManager;
        _logger = logger;
    }

    [BindProperty]
    public LoginViewModel Input { get; set; }

    [BindProperty]
    public bool IsVerifiedUser { get; set; }

    public bool IsAdmin { get; set; }

    public IList<AuthenticationScheme> ExternalLogins { get; set; }

    public string ReturnUrl { get; set; }

    [TempData]
    public string ErrorMessage { get; set; }

    public async Task OnGetAsync(string returnUrl = null)
    {
        if (!string.IsNullOrEmpty(ErrorMessage))
        {
            ModelState.AddModelError(string.Empty, ErrorMessage);
        }

        returnUrl = returnUrl ?? Url.Content("~/");

        // Clear the existing external cookie to ensure a clean login process
        await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

        ReturnUrl = returnUrl;
    }

    public async Task<IActionResult> OnPostAsync(string returnUrl = null)
    {
        returnUrl = returnUrl ?? Url.Content("~/");

        if (ModelState.IsValid)
        {
            var user = await _signInManager.UserManager.Users.FirstOrDefaultAsync(u => u.UserName == Input.UserName || u.Email == Input.UserName);
            if (user == null)
            {
                ModelState.AddModelError(string.Empty, "Username or Password is not correct.");
                return Page();
            }

            var result = await _signInManager.CheckPasswordSignInAsync(user, Input.Password, lockoutOnFailure: true);
            if (result.Succeeded)
            {
                if (IsVerifiedUser)
                {
                    if (string.IsNullOrWhiteSpace(Input.Database))
                    {
                        ModelState.AddModelError(nameof(Input.Database), "Database name is required.");
                        return Page();
                    }
                    else
                    {
                        return await SignInAsync(user, Input.Database, returnUrl);
                    }
                }
            }
        }
        return Page();
    }

    private async Task<IActionResult> SignInAsync(ApplicationUser user, string databaseName, string returnUrl = null)
    {
        var result = await _signInManager.CheckPasswordSignInAsync(user, Input.Password, lockoutOnFailure: true);
        if (result.Succeeded)
        {
            var customClaims = new[]{
                    new Claim(ClaimConstants.DatabaseClaim, databaseName)
                };
            await _signInHelper.SignInUserAsync(user, Input.RememberMe, customClaims);

            HttpContext.Session.SetString("DbProviderType", Input.Provider.ToString());
            _logger.LogInformation("User logged in.");
            return LocalRedirect(returnUrl);
        }
    }
}
[AllowAnonymous]
公共类LoginModel:PageModel
{
私有只读MyDbContext\u context;
专用只读签名器\u签名器;
专用只读签名管理器\u签名管理器;
专用只读ILogger\u记录器;
公共登录模型(MyDbContext上下文,
SignInManager SignInManager,
签名者签名者签名者,
ILogger(记录器)
{
_上下文=上下文;
_signInHelper=signInHelper;
_signInManager=signInManager;
_记录器=记录器;
}
[BindProperty]
公共LoginViewModel输入{get;set;}
[BindProperty]
public bool IsVerifiedUser{get;set;}
公共bool IsAdmin{get;set;}
公共IList外部登录{get;set;}
公共字符串ReturnUrl{get;set;}
[临时数据]
公共字符串错误消息{get;set;}
公共异步任务OnGetAsync(字符串返回URL=null)
{
如果(!string.IsNullOrEmpty(ErrorMessage))
{
AddModelError(string.Empty,ErrorMessage);
}
returnUrl=returnUrl??Url.Content(“~/”);
//清除现有的外部cookie以确保干净的登录过程
等待HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
ReturnUrl=ReturnUrl;
}
公共异步任务OnPostAsync(字符串returnUrl=null)
{
returnUrl=returnUrl??Url.Content(“~/”);
if(ModelState.IsValid)
{
var user=wait _signInManager.UserManager.Users.FirstOrDefaultAsync(u=>u.UserName==Input.UserName | | u.Email==Input.UserName);
if(user==null)
{
AddModelError(string.Empty,“用户名或密码不正确”);
返回页();
}
var result=await _signInManager.CheckPasswordSignInAsync(用户、输入、密码、锁定失败:true);
if(result.successed)
{
如果(IsVerifiedUser)
{
if(string.IsNullOrWhiteSpace(Input.Database))
{
AddModelError(nameof(Input.Database),“需要数据库名”);
返回页();
}
其他的
{
return wait SignInAsync(用户、Input.Database、returnUrl);
}
}
}
}
返回页();
}
专用异步任务符号同步(ApplicationUser用户,字符串databaseName,字符串returnUrl=null)
{
var result=await _signInManager.CheckPasswordSignInAsync(用户、输入、密码、锁定失败:true);
if(result.successed)
{
var customClaims=new[]{
新声明(ClaimConstants.DatabaseClaim,databaseName)
};
等待(user、Input.RememberMe、customClaims)signInHelper.signinUserSync ;;
HttpContext.Session.SetString(“DbProviderType”,Input.Provider.ToString());
_logger.LogInformation(“用户登录”);
返回LocalRedirect(returnUrl);
}
}
}
在login.cshtml中,用户名和密码输入旁边有一个下拉列表,可以从用户可访问的数据库中进行选择

下面是我的中间件配置:

public class Startup
{
    public IConfiguration Configuration { get; }
    private readonly IHostingEnvironment _hostingEnvironment;

    public Startup(IConfiguration configuration, IHostingEnvironment env)
    {
        Configuration = configuration;
        _hostingEnvironment = env;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        Inflector.Inflector.SetDefaultCultureFunc = () => new CultureInfo("EN-US");

        services.Configure<CookiePolicyOptions>(options =>
        {
            options.CheckConsentNeeded = context => false;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddDistributedMemoryCache();

        services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromSeconds(3000);
            options.Cookie.HttpOnly = true;
        });

        services.AddDbContext<MyDbContext>(options =>
            options.UseSqlServer(Configuration["ConnectionStrings:Cn1"], b => b.MigrationsAssembly("DAL")));

        services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores<MyDbContext>()

            .AddDefaultTokenProviders()
            .AddDefaultUI(UIFramework.Bootstrap4);

        services.Configure<IdentityOptions>(options =>
        {
            options.User.RequireUniqueEmail = true;
        });


        // Adds IdentityServer.
        services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryPersistedGrants()
            .AddInMemoryIdentityResources(IdentityServerConfig.GetIdentityResources())
            .AddInMemoryApiResources(IdentityServerConfig.GetApiResources())
            .AddInMemoryClients(IdentityServerConfig.GetClients())

            .AddAspNetIdentity<ApplicationUser>()
            .AddProfileService<ProfileService>();

        string applicationUrl = Configuration["ApplicationUrl"].TrimEnd('/');

        services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = applicationUrl;
                options.SupportedTokens = SupportedTokens.Jwt;
                options.RequireHttpsMetadata = false;
                options.ApiName = IdentityServerConfig.ApiName;
            });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
                .AddJsonOptions(
                    options => options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore
        );

        services.AddTransient<SecondDbContext>(provider => provider.GetService<ApplicationDbContextFactory>().Create());
        services.AddScoped<ApplicationDbContextFactory>();


        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new Info { Title = IdentityServerConfig.ApiFriendlyName, Version = "v1" });
            c.OperationFilter<AuthorizeCheckOperationFilter>();
            c.AddSecurityDefinition("oauth2", new OAuth2Scheme
            {
                Type = "oauth2",
                Flow = "password",
                TokenUrl = $"{applicationUrl}/connect/token",
                Scopes = new Dictionary<string, string>()
                {
                   { IdentityServerConfig.ApiName, IdentityServerConfig.ApiFriendlyName }
                }
            });
        });

        var mappingConfig = new MapperConfiguration(cfg =>
        {
            cfg.AddProfile<AutoMapperProfile>();
        });

        IMapper mapper = mappingConfig.CreateMapper();
        services.AddSingleton(mapper);

        services.AddScoped<IAccountManager, AccountManager>();

        // Auth Handlers
        services.AddSingleton<IAuthorizationHandler, ViewUserAuthorizationHandler>();
        services.AddSingleton<IAuthorizationHandler, ManageUserAuthorizationHandler>();
        services.AddSingleton<IAuthorizationHandler, ViewRoleAuthorizationHandler>();
        services.AddSingleton<IAuthorizationHandler, AssignRolesAuthorizationHandler>();

        services.AddTransient<IRepositoryFactory, RepositoryFactory>();
        services.AddScoped(typeof(SqlRepository<>));

        services.AddTransient(typeof(IService<>), typeof(BaseService<>));
        services.AddTransient(typeof(IServiceWithTypeId<,>), typeof(BaseService<,>));

        services.AddTransient<IServiceFactory, ServiceFactory>();

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, MyDbContext context, ILoggerFactory loggerFactory, IApplicationLifetime applicationLifetime, IServiceProvider serviceProvider)
    {
        loggerFactory.AddFile(Configuration.GetSection("Logging"));

        Utilities.ConfigureLogger(loggerFactory);
        EmailTemplates.Initialize(env);

        app.UseSession();
        app.UseIdentityServer();

        app.UseMvc();
    }
}
公共类启动
{
公共IConfiguration配置{get;}
私有只读IHostingEnvironment\u hostingEnvironment;
公共启动(IConfiguration配置,IHostingEnvironment环境)
{
配置=配置;
_hostingEnvironment=env;
}
public void配置服务(IServiceCollection服务)
{
definctor.definctor.SetDefaultCultureFunc=()=>new CultureInfo(“EN-US”);
配置(选项=>
{
options.checkApprovered=context=>false;
options.MinimumSameSitePolicy=SameSiteMode.None;
});
AddDistributedMemoryCache();
services.AddSession(选项=>
{
options.IdleTimeout=TimeSpan.FromSeconds(3000);
options.Cookie.HttpOnly=true;
});
services.AddDbContext(选项=>
options.UseSqlServer(配置[“ConnectionString:Cn1”],b=>b.MigrationsAssembly(“DAL”));
服务.额外性()
.AddEntityFrameworkStores()
AddDefaul先生
services.AddScoped<SignInHelper<ApplicationUser>>();