C# 如何将自定义HttpContextAccessor添加到服务ASP.NET核心

C# 如何将自定义HttpContextAccessor添加到服务ASP.NET核心,c#,asp.net-core,httpcontext,C#,Asp.net Core,Httpcontext,我想向asp.net core中的服务添加自定义HttpContextAccessor 这是正确的方法吗 在配置服务方法时: var env=services.BuildServiceProvider().GetRequiredService(); 然后添加海关索赔(这些索赔将由另一个类提取) if(env.IsDevelopment()) { var索赔=新列表(); 添加(新的索赔(ClaimTypes.Name,“test”); 添加(新的索赔(ClaimTypes.Role,“Oper

我想向asp.net core中的服务添加自定义HttpContextAccessor

这是正确的方法吗

在配置服务方法时:

var env=services.BuildServiceProvider().GetRequiredService();
然后添加海关索赔(这些索赔将由另一个类提取)

if(env.IsDevelopment())
{
var索赔=新列表();
添加(新的索赔(ClaimTypes.Name,“test”);
添加(新的索赔(ClaimTypes.Role,“Operator”);
索赔。添加(新索赔(“http://schemas.microsoft.com/identity/claims/objectidentifier“,”af4ab79d-f75c-44be-b8dd-test“);
添加(新的索赔(“公司名称”、“测试”);
services.AddSingleton(sp=>newDefaultHttpContext()
{
用户=新索赔人(新索赔人(索赔)),
});
}

这样一来:
IHttpContextAccessor
DefaultHttpContext
的类型都不匹配,有没有办法解决这个问题,或者如何正确地解决这个问题?

您能试一下这种方法吗?我在集成测试中使用它来通过身份验证,因此我认为它可能适用于您的场景

public class TestAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
    public TestAuthenticationHandler(
        IOptionsMonitor<AuthenticationSchemeOptions> options,
        ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
        : base(options, logger, encoder, clock)
    {
    }

    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        var claims = new[]
        {
            new Claim(JwtClaimTypes.Subject, MasterData.CurrentUserId),
            new Claim(JwtClaimTypes.Name, "test@gmail.com"),
            new Claim(JwtClaimTypes.Email, "test@gmail.com"),
            new Claim(JwtClaimTypes.Role, "Admin"),
        };
        var identity = new ClaimsIdentity(claims, "Test");
        var principal = new ClaimsPrincipal(identity);
        var ticket = new AuthenticationTicket(principal, "Test");

        var result = AuthenticateResult.Success(ticket);

        return Task.FromResult(result);
    }
}
公共类TestAuthenticationHandler:AuthenticationHandler { 公共TestAuthenticationHandler( IOPTIONS监视器选项, iLogger(出厂记录器、URLCoder编码器、ISystemClock时钟) :基本(选项、记录器、编码器、时钟) { } 受保护的覆盖任务handleAuthenticateAync() { 风险值索赔=新[] { 新声明(JwtClaimTypes.Subject,MasterData.CurrentUserId), 新索赔(JwtClaimTypes.Name,“test@gmail.com"), 新索赔(JwtClaimTypes.Email,“test@gmail.com"), 新声明(JwtClaimTypes.Role,“Admin”), }; var标识=新的索赔实体(索赔,“测试”); var principal=新的ClaimsPrincipal(身份); var票证=新的认证票证(主体,“测试”); var结果=AuthenticateResult.Success(票证); 返回Task.FromResult(结果); } } 在启动时注册处理程序

services.AddAuthentication("Test")
                            .AddScheme<AuthenticationSchemeOptions, TestAuthenticationHandler>
services.AddAuthentication(“测试”)
.AddScheme

您的方案是什么?实际上,我认为您需要在中间件中向httpcontext用户添加声明。我如何才能做到这一点?我的场景是,我有一个API通过Azure AD进行授权,对于开发环境,我希望有一个硬编码的用户,因为我在其他类中使用IHttpContextAccessor来提取用户声明/