具有EF Core迁移和IHttpContextAccessor的ASP.NET Core(3.1)

多米尼克

我正在尝试为我的asp.net核心api项目添加ef核心迁移。不幸的是,迁移必须处理添加迁移时遇到的一些麻烦,因为我正在将IHttpContextAccessor注入我的提供程序之一:/

我打电话给services.AddHttpContextAccessor();services.AddDbContext<SCContext>(builder => builder.UseSqlServer(connectionstring));在我的startup.cs中。

如果我正在运行>dotnet run并执行一些请求,则一切正常。但是,如果显示了我正在尝试运行>dotnet ef migrations add InitialCreate以下日志的信息(两个命令都在api项目目录路径中执行):

Build started...
Build succeeded.
System.NullReferenceException: Object reference not set to an instance of an object.
   at SocietyCloud.Services.Provider.CredentialsProvider..ctor(IHttpContextAccessor httpContextAccessor) in E:\Bibliotheken\Projects\societycloud\Application\SocietyCloud.Services\Provider\CredentialsProvider.cs:line 15
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_2.<FindContextTypes>b__11()
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
   at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
   at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.<>c__DisplayClass0_0.<.ctor>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Object reference not set to an instance of an object.

有人遇到过同样的问题吗?

启动文件

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddDefaultPolicy(builder =>
            builder.SetIsOriginAllowed(_ => true)
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());
    });
    services.AddControllers();
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "TEST", Version = "v1" });
    });
    AutoMapperConfig.Configure(services);
    OptionsConfig.Configure(services, Configuration);
    AuthenticationConfig.Configure(services, Configuration);
    DependencyConfig.Configure(services, Configuration);
}

DependencyConfig.cs

public static void Configure(IServiceCollection services, IConfiguration configuration)
{
    // Register provider
    services.AddHttpContextAccessor();
    var openibanurl = configuration[$"{nameof(ExternalApisOptions)}:{nameof(ExternalApisOptions.OpenIbanUrl)}"];
    services.AddHttpClient<IOpenIbanProvider, OpenIbanProvider>(configure => configure.BaseAddress = new Uri(openibanurl));

    // Register DBContext
    var connectionstring = configuration[$"{nameof(AzureOptions)}:{nameof(AzureOptions.SqlConnectionstring)}"];
    services.AddDbContext<SCContext>(builder => builder.UseSqlServer(connectionstring));

    // Register services
    foreach (var (Contract, Implementation) in typeof(MembershipsService).Assembly.GetTypesWithImplementations<IService>())
        services.AddScoped(Contract, Implementation);

    // Register validator
    services.AddScoped<IViewModelValidator<VMAddMembership>, VMAddMembershipValidator>();
}

CredentialsProvider.cs

public class CredentialsProvider : ICredentialsProvider
{
    public Guid? AccountId { get; private set; }
    public Guid? SocietyId { get; private set; }

    public CredentialsProvider(IHttpContextAccessor httpContextAccessor)
    {
        if (httpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
        {
            AccountId = GetGuid(httpContextAccessor.HttpContext, SCClaims.AccountId);
            SocietyId = GetGuid(httpContextAccessor.HttpContext, SCClaims.SocietyId);
        }
    }

    private Guid? GetGuid(HttpContext context, SCClaims claim)
    {
        if (Guid.TryParse(context.User.Claims?.FirstOrDefault(x => x.Type == Enum.GetName(typeof(SCClaims), claim))?.Value, out var societyid))
            return societyid;
        return null;
    }
}
恩科西

HttpContextCredentialsProviderwill的构造函数中访问将会失败,因为您将无法在生命周期中过早访问它,而无法填充上下文及其成员

public class CredentialsProvider : ICredentialsProvider {
    private readonly IHttpContextAccessor httpContextAccessor;

    public CredentialsProvider(IHttpContextAccessor httpContextAccessor) {
        this.httpContextAccessor = httpContextAccessor;
    }

    public Guid? AccountId =>  GetGuid(SCClaims.AccountId);
    public Guid? SocietyId =>  GetGuid(SCClaims.SocietyId);

    private Guid? GetGuid(SCClaims claim) {
        if (Guid.TryParse(httpContextAccessor.HttpContext.User?.Claims?
                .FirstOrDefault(x => x.Type == Enum.GetName(typeof(SCClaims), claim))?.Value,
             out var societyid)
        )
            return societyid;
        return null;
    }
}

尝试避免在构造函数中执行过多的逻辑。它们主要用于分配初始值。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

在具有 EF Core 迁移的 Net Core 类库上使用 settings.json

来自分类Dev

.NET Core EF Select 对象,其中关系具有

来自分类Dev

具有在SingleView中创建的实体列表的Asp.Net Core MVC EF模型

来自分类Dev

ASP.NET Core MVC 和 EF Core 1.1

来自分类Dev

带有ASP.NET Core 3.0和EF Core的多租户应用程序

来自分类Dev

带有EF Core和CosmosDB的ASP.Net Core-IdentityRole问题

来自分类Dev

EF Core 迁移可能具有破坏性?

来自分类Dev

EF7 .NET Core 1 RC2添加迁移失败

来自分类Dev

ASP.Net Core / EF Core:添加迁移后,身份用户类和自定义类之间存在多对多关系,堆栈溢出

来自分类Dev

获取ASP.NET Core 1中的所有缓存

来自分类Dev

asp .net 和 asp .net core 有什么区别?

来自分类Dev

将IHttpContextAccessor注入ApplicationDbContext ASP.NET Core 1.0

来自分类Dev

EF Core 3 1对0关系问题

来自分类Dev

Net Core 3.0 Linux Azure Web App IHttpContextAccessor具有空上下文

来自分类Dev

将'hd'参数附加到带有身份标识3的redirectUrl ASP.NET Core 1

来自分类Dev

将Asp.Net Core RC1迁移到RC2后的问题

来自分类Dev

ASP.NET Core RC1到1.0.0的迁移错误

来自分类常见问题

ASP.NET 5,.NET Core和ASP.NET Core 5有什么区别?

来自分类Dev

具有503服务的Asp Net Core 3示例不可用

来自分类Dev

创建项目ASP.NET Core(.NET Core)和ASP.NET Core(.NET Framework)有什么区别

来自分类Dev

ASP net Core Razor Pages - EF 和视图的拆分模型

来自分类Dev

通过EF迁移将ASP.NET Core部署到Azure

来自分类Dev

Xamarin Forms,Sqlite,EF Core 3,迁移和大量混淆

来自分类Dev

.NET Standard和.NET Core 3.x或ASP.NET Core 3.x

来自分类Dev

SHA1(c#)-与.Net 3和.Net Core不同的结果

来自分类Dev

Azure中具有MVC和ASP.NET Core的Outputcache IIS

来自分类Dev

具有身份和ExternalLogin的ASP.NET Core 3.1中基于角色的授权

来自分类Dev

共享cookie .net Core 3和Asp.net

来自分类Dev

具有简单注入器的ASP.NET Core

Related 相关文章

  1. 1

    在具有 EF Core 迁移的 Net Core 类库上使用 settings.json

  2. 2

    .NET Core EF Select 对象,其中关系具有

  3. 3

    具有在SingleView中创建的实体列表的Asp.Net Core MVC EF模型

  4. 4

    ASP.NET Core MVC 和 EF Core 1.1

  5. 5

    带有ASP.NET Core 3.0和EF Core的多租户应用程序

  6. 6

    带有EF Core和CosmosDB的ASP.Net Core-IdentityRole问题

  7. 7

    EF Core 迁移可能具有破坏性?

  8. 8

    EF7 .NET Core 1 RC2添加迁移失败

  9. 9

    ASP.Net Core / EF Core:添加迁移后,身份用户类和自定义类之间存在多对多关系,堆栈溢出

  10. 10

    获取ASP.NET Core 1中的所有缓存

  11. 11

    asp .net 和 asp .net core 有什么区别?

  12. 12

    将IHttpContextAccessor注入ApplicationDbContext ASP.NET Core 1.0

  13. 13

    EF Core 3 1对0关系问题

  14. 14

    Net Core 3.0 Linux Azure Web App IHttpContextAccessor具有空上下文

  15. 15

    将'hd'参数附加到带有身份标识3的redirectUrl ASP.NET Core 1

  16. 16

    将Asp.Net Core RC1迁移到RC2后的问题

  17. 17

    ASP.NET Core RC1到1.0.0的迁移错误

  18. 18

    ASP.NET 5,.NET Core和ASP.NET Core 5有什么区别?

  19. 19

    具有503服务的Asp Net Core 3示例不可用

  20. 20

    创建项目ASP.NET Core(.NET Core)和ASP.NET Core(.NET Framework)有什么区别

  21. 21

    ASP net Core Razor Pages - EF 和视图的拆分模型

  22. 22

    通过EF迁移将ASP.NET Core部署到Azure

  23. 23

    Xamarin Forms,Sqlite,EF Core 3,迁移和大量混淆

  24. 24

    .NET Standard和.NET Core 3.x或ASP.NET Core 3.x

  25. 25

    SHA1(c#)-与.Net 3和.Net Core不同的结果

  26. 26

    Azure中具有MVC和ASP.NET Core的Outputcache IIS

  27. 27

    具有身份和ExternalLogin的ASP.NET Core 3.1中基于角色的授权

  28. 28

    共享cookie .net Core 3和Asp.net

  29. 29

    具有简单注入器的ASP.NET Core

热门标签

归档