Как использовать ApplicationClaimsPrincipalFactory в ядре MVC 2.2 - PullRequest
1 голос
/ 04 мая 2019

У меня есть этот код в ApplicationClaimsPrincipalFactory на ASP.Net MVC Core 2.2:

public class ApplicationClaimsPrincipalFactory : UserClaimsPrincipalFactory<TblUsers, TblOrganizationChart>
{
    public static readonly string PhotoFileName = nameof(PhotoFileName);

    private readonly IOptions<IdentityOptions> _optionsAccessor;
    private readonly IApplicationRoleManager _roleManager;
    private readonly IApplicationUserManager _userManager;

    public ApplicationClaimsPrincipalFactory(
        IApplicationUserManager userManager,
        IApplicationRoleManager roleManager,
        IOptions<IdentityOptions> optionsAccessor)
        : base((UserManager<TblUsers>)userManager, (RoleManager<TblOrganizationChart>)roleManager, optionsAccessor)
    {
        _userManager = userManager;
        _userManager.CheckArgumentIsNull(nameof(_userManager));

        _roleManager = roleManager;
        _roleManager.CheckArgumentIsNull(nameof(_roleManager));

        _optionsAccessor = optionsAccessor;
        _optionsAccessor.CheckArgumentIsNull(nameof(_optionsAccessor));
    }

    public override async Task<ClaimsPrincipal> CreateAsync(TblUsers user)
    {
        var principal = await base.CreateAsync(user);
        addCustomClaims(user, principal);
        return principal;
    }

    private static void addCustomClaims(TblUsers user, IPrincipal principal)
    {
        ((ClaimsIdentity)principal.Identity).AddClaims(new[]
        {
        new Claim(ClaimTypes.NameIdentifier, user.Id.ToString(), ClaimValueTypes.Integer),
        new Claim(ClaimTypes.GivenName, user.TblPerson.FullName ?? string.Empty)
    });
    }
}

при выполнении строки var principal = await base.CreateAsync(user); У меня есть исключение:

StackTrace ="at System.Security.Claims.Claim..ctor (Строковый тип, Строковое значение, Строковое значениеType, Строковый издатель, Строковый originalIssuer, субъект ClaimsIdentity, String propertyKey, String propertyValue) \ r \ n в System.Security.Claims.Claim..ctor (Строковый тип, String va ...

Я гость base - пусто, но я не знаю, что мне нужно делать.

Startup.cs:

`открытый класс Startup {открытый запуск (конфигурация IConfiguration) {Configuration = configuration;}

    public IConfiguration Configuration { get; }

    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.Configure<SiteSettings>(options => Configuration.Bind(options));
        IdentityServicesRegistry.AddCustomServices(services);


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

        services.AddDbContext<AbfaContext>(options =>

            options
            .UseSqlServer(Configuration.GetConnectionString("Default")));

        services.AddDbContext<AbfaContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("AbfaConnectionString"), x => x.UseNetTopologySuite()));


        services.AddLocalization(options => options.ResourcesPath = "Resources");

        services.AddMvc(options =>
        {
            options.UseYeKeModelBinder();
            options.AllowEmptyInputInBodyModelBinding = true;
            options.EnableEndpointRouting = false;
        }).AddNewtonsoftJson(options =>
                           options.SerializerSettings.ContractResolver =
                              new CamelCasePropertyNamesContractResolver())
        .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
        .AddDataAnnotationsLocalization()
        .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
            .AddDataAnnotationsLocalization();


        services.AddDNTCommonWeb();
        services.AddHttpContextAccessor();



        var thisServiceProvider = services.BuildServiceProvider();
        var accessor = thisServiceProvider.GetService<IHttpContextAccessor>();
        AddLog.SetHttpContextAccessor(accessor);
        return thisServiceProvider;
    }

    public void Configure(ILoggerFactory loggerFactory, IApplicationBuilder app, IHostingEnvironment env)
    {
        loggerFactory.AddDbLogger(serviceProvider: app.ApplicationServices, minLevel: LogLevel.Warning);
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();

        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
            app.UseHttpsRedirection();
        }
        app.UseFileServer(new FileServerOptions
        {
            EnableDirectoryBrowsing = false
        });
        app.UseStaticFiles();
        app.UseCustomServices();
        app.UseCookiePolicy();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "areas",
                template: "{area:exists}/{controller=Account}/{action=Index}/{id?}");

            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}`
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...