Getting null value for configuration/connection string - asp.net-core-mvc

I have recently upgraded my project from dotnet core v.1.0.0 to v.1.0.4. I am using the same code in each of the Startup.cs files. V.1.0.0 works fine, .4 does not. Visual Studio 2017.
System.ArgumentNullException occurred
HResult=0x80004003
Message=Value cannot be null.
Source=<Cannot evaluate the exception source>
StackTrace:
at Microsoft.EntityFrameworkCore.Utilities.Check.NotEmpty(String value, String parameterName)
at Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder, String connectionString, Action`1 sqlServerOptionsAction)
at ApostilleDNCv2.Startup.<ConfigureServices>b__4_0(DbContextOptionsBuilder options) in c:\users\kenn.kinnaird\documents\visual studio 2017\Projects\ApostilleDNCv2\ApostilleDNCv2\Startup.cs:line 34
at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.DbContextOptionsFactory[TContext](IServiceProvider applicationServiceProvider, Action`2 optionsAction)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider)
at Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
at Microsoft.AspNetCore.Mvc.Internal.TypeActivatorCache.CreateInstance[TInstance](IServiceProvider serviceProvider, Type implementationType)
at Microsoft.AspNetCore.Mvc.Controllers.DefaultControllerFactory.CreateController(ControllerContext context)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextResourceFilter>d__22.MoveNext()
My code (both version):
Startup.cs-
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("ApostillesTest")));
services.AddMvc();
services.AddDistributedMemoryCache();
services.AddScoped<ICountryRepository, CountryRepository>();
appsettings.json-
"ConnectionStrings": {
"ApostillesTest": "Server=TESTSQLCORP;Database=Apostilles;Trusted_Connection=True;Persist Security Info=True",
"DefaultConnection": "Server=TESTSQLCORP;Database=Apostilles;Trusted_Connection=True"
}
I have looked at other solutions here; none have helped.
Any help will be appreciated.

Related

Internet Service Error on Microsoft.Bot.Builder.Dialogs.Adaptive.Runtime on dot net 6

i attempt to migrate bot framework composer dot net 3.1 project to dot net 6
upon testing i hit Internet Service Error, any insight would be appreciated.
ArgumentNullException: Value cannot be null. (Parameter 'adaptiveDialogId')
Microsoft.Bot.Builder.Dialogs.Adaptive.AdaptiveDialogBot..ctor(string adaptiveDialogId, string languageGeneratorId, ResourceExplorer resourceExplorer, ConversationState conversationState, UserState userState, SkillConversationIdFactoryBase skillConversationIdFactoryBase, LanguagePolicy languagePolicy, BotFrameworkAuthentication botFrameworkAuthentication, IBotTelemetryClient telemetryClient, IEnumerable scopes, IEnumerable pathResolvers, IEnumerable dialogs, ILogger logger)
Microsoft.Bot.Builder.Dialogs.Adaptive.Runtime.ConfigurationAdaptiveDialogBot..ctor(IConfiguration configuration, ResourceExplorer resourceExplorer, ConversationState conversationState, UserState userState, SkillConversationIdFactoryBase skillConversationIdFactoryBase, LanguagePolicy languagePolicy, BotFrameworkAuthentication botFrameworkAuthentication, IBotTelemetryClient telemetryClient, IEnumerable scopes, IEnumerable pathResolvers, IEnumerable dialogs, ILogger logger)
System.RuntimeMethodHandle.InvokeMethod(object target, ref Span arguments, Signature sig, bool constructor, bool wrapExceptions)
System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor<TArgument, TResult>.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite callSite, RuntimeResolverContext context)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor<TArgument, TResult>.VisitCallSite(ServiceCallSite callSite, TArgument argument)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
Microsoft.Extensions.DependencyInjection.ServiceProvider.CreateServiceAccessor(Type serviceType)
System.Collections.Concurrent.ConcurrentDictionary<TKey, TValue>.GetOrAdd(TKey key, Func<TKey, TValue> valueFactory)
Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
lambda_method8(Closure , IServiceProvider , object[] )
Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider+<>c__DisplayClass7_0.b__0(ControllerContext controllerContext)
Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider+<>c__DisplayClass6_0.g__CreateController|0(ControllerContext controllerContext)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Thanks AP01 for dropping your knowledge
Unfortunately, the adaptiveDialogId is embedded in library Microsoft.Bot.Builder.Dialogs.Adaptive.Runtime in which I cannot debug
however, inspired by your advice
I modify the build target not from scratch, but simply upgrade the dot net target straight from 3.1 to 6
as it turns out the problems caused by nullable validation in the Project File, this causes dot net 3.1 libraries not working
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Platforms>x64</Platforms>
**<Nullable>enable</Nullable>**
...
</PropertyGroup>

How to add migrations for Entity Framework in a Xamarin Forms project?

I am trying to get the EF migrations to work in a Xamarin Forms project. I have a DbContext for a SQLite database:
public class TestDbContext : DbContext
{
public DbSet<Item> Items { get; set; }
public TestDbContext()
{
SQLitePCL.Batteries_V2.Init();
this.Database.EnsureCreated();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string dbPath = Path.Combine(FileSystem.AppDataDirectory, "testDb.db3");
optionsBuilder
.UseSqlite($"Filename={dbPath}");
}
}
I installed the Microsoft.EntityFrameworkCore.Tools nuget for the standard library, but it did not work. Starting from this, I added a Dummy .NET Core project.
I referenced the .NET Standard library (2.1) in the Dummy (Xamarin Forms project)
I installed the Microsoft.EntityFrameworkCore.Sqlite and Microsoft.EntityFrameworkCore.Tools nuget packages into the dummy project as well
I implemented an IDesignTimeDbContextFactory in the .net standard library like this:
public class DesignTimeFactory : IDesignTimeDbContextFactory<TestDbContext>
{
public TestDbContext CreateDbContext(string[] args)
{
return new TestDbContext();
}
}
When I run the command PM> Add-Migration InitialCreate -P XamarinEFTest -S EFDummy I get an exception:
Build started...
Build succeeded.
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
---> Xamarin.Essentials.NotImplementedInReferenceAssemblyException: This functionality is not implemented in the portable version of this assembly. You should reference the NuGet package from your main application project in order to reference the platform-specific implementation.
at Xamarin.Essentials.FileSystem.get_PlatformAppDataDirectory()
at Xamarin.Essentials.FileSystem.get_AppDataDirectory()
at XamarinEFTest.TestDbContext.OnConfiguring(DbContextOptionsBuilder optionsBuilder) in C:\Users\szabk\source\repos\XamarinEFTest\XamarinEFTest\XamarinEFTest\TestDbContext.cs:line 24
at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
at Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<System.IServiceProvider>.get_Instance()
at Microsoft.EntityFrameworkCore.Infrastructure.Internal.InfrastructureExtensions.GetService[TService](IInfrastructure`1 accessor)
at Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure`1 accessor)
at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.get_Dependencies()
at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.EnsureCreated()
at XamarinEFTest.TestDbContext..ctor() in C:\Users\szabk\source\repos\XamarinEFTest\XamarinEFTest\XamarinEFTest\TestDbContext.cs:line 19
at XamarinEFTest.DesignTimeFactory.CreateDbContext(String[] args) in C:\Users\szabk\source\repos\XamarinEFTest\XamarinEFTest\XamarinEFTest\DesignTimeFactory.cs:line 12
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContextFromFactory(Type factory, Type contextType)
at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass16_0.<FindContextFactory>b__1()
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, String namespace)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType, String namespace)
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)
Exception has been thrown by the target of an invocation.
I have VS 2019 16.8.4, I created the test xamarin project from the layout template with the slider menu.
What do I need to do?
Edit: Maybe I need to setup the Core project with a different SQLite driver and with a different DesignTimeFactory? But how would this work? I need the migrations to work in the phone in the end.
The Xamarin.Essentials FileSystem.AppDataDirectory doesn't work on Windows/Mac, where you're trying to create the migration.
Use this sqlite database path for creating the migrations:
optionsBuilder.UseSqlite($"Data Source=migrations.db3");
This path is relative and you'll end up with a migrations.db3 file created in your project folder. Just ignote the .db file, it's only purpose was to create the migration.
EDIT:
I've been using this DbContext in my app and it works just fine.
public class MyDbContext : DbContext
{
private string _databasePath;
public DbSet<MyEntity> Issues { get; set; }
[Obsolete("Don't use this for production. This is only for creating migrations.")]
public MyDbContext() : this("nothing.db")
{
}
public MyDbContext(string dbPath)
{
_databasePath = dbPath;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlite($"Data Source={_databasePath}");
}
}
}

Core scaffolding Oracle DB will give multiple ID(primary key's) as result

When I scaffold this Oracle DB (database -first) and it generates me all models, contexts, FK relations ect. But it gives me an error in the context when I start Querying.
(simple things as select * from (any Table))
The follow error comes up.
System.InvalidOperationException
HResult=0x80131509
Message=The properties 'Address.AddressId', 'Address.AddressItemId'
are configured to use 'Identity' value generator and are mapped to the
same table '[DBName].ADDRESS'. Only one column per table can be
configured as 'Identity'. Call 'ValueGeneratedNever' for properties
that should not use 'Identity'.
Source=Oracle.EntityFrameworkCore
StackTrace:
at
Oracle.EntityFrameworkCore.Internal.OracleModelValidator.ValidateSharedColumnsCompatibility(IReadOnlyList`1
mappedTypes, String tableName)
at
Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.ValidateSharedTableCompatibility(IModel
model)
at
Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.Validate(IModel
model)
at
Oracle.EntityFrameworkCore.Internal.OracleModelValidator.Validate(IModel
model)
at
Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ValidatingConvention.Apply(InternalModelBuilder
modelBuilder)
at
Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnModelBuilt(InternalModelBuilder
modelBuilder)
at
Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnModelBuilt(InternalModelBuilder
modelBuilder)
at Microsoft.EntityFrameworkCore.Metadata.Internal.Model.Validate()
at Microsoft.EntityFrameworkCore.ModelBuilder.FinalizeModel()
at
Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext
context, IConventionSetBuilder conventionSetBuilder, IModelValidator
validator)
at
Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.<>c__DisplayClass5_0.b__1()
at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
at System.Lazy`1.ExecutionAndPublication(LazyHelper
executionAndPublication, Boolean useDefaultConstructor)
at System.Lazy`1.CreateValue()
at System.Lazy`1.get_Value()
at
Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext
context, IConventionSetBuilder conventionSetBuilder, IModelValidator
validator)
at
Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()
at
Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
at
Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.<>c.b__7_2(IServiceProvider
p)
at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite
factoryCallSite, ServiceProviderEngineScope scope)
at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite
callSite, TArgument argument)
at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite
scopedCallSite, ServiceProviderEngineScope scope)
at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite
callSite, TArgument argument)
at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite
constructorCallSite, ServiceProviderEngineScope scope)
at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite
callSite, TArgument argument)
at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite
scopedCallSite, ServiceProviderEngineScope scope)
at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite
callSite, TArgument argument)
at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(IServiceCallSite
callSite, ServiceProviderEngineScope scope)
at
Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.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.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider
provider, Type serviceType)
at
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider
provider)
at
Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
at
Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
at
Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
at Microsoft.EntityFrameworkCore.DbContext.get_Model()
at
Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityType()
at
Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.CheckState()
at
Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityQueryable()
at
Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.System.Linq.IQueryable.get_Provider()
at System.Linq.Queryable.Count[TSource](IQueryable`1 source)
at OracleConsoleApp.Program.Main(String[] args) in
C:\GitPlayGround\OracleConsoleApp\OracleConsoleApp\Program.cs:line 47
I need to use the FK connections in this complex structure.
I have no experience with Oracle, nor with Oracle.EntityFrameworkCore (2.2.6, application core 2.2)
Can anyone advise me what to do, Can't find a clue to start to solve this.
After a deep research, my colleague came with the solution.
In Oracle generated value's work different. With the database first it sets the data annotation ValueGeneratedOnAdd();.
This is not a working model and context.
So selective deleting this ValueGeneratedOnAdd() will result in a working result and solves the problem.

WebAPI 2.2 on .Net core with IdentityServer3.AccessTokenValidation throws NullreferenceException

I'm having a hard time getting this to work. Currently I already have got an IdentityServer4, an Angular2SPA and a WebAPI 2.2 for ODATA running. All services are running in individual projects on asp.net core.
IdentityServer4
Angular2SPA
WebAPI2.2 .core targeting .Net462
The WebAPI runs fine as long as i dont try to connect it to the IdentityServer.
I have verified that my setup, beside the WebAPI, works correctly.
I have also tested the WebAPI connection configuration with the IdentityServer3.Samples on Github by connecting their WebAPISample with my IdentityServer.
WebAPI
Startup.cs
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
//services.AddAuthorization();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(LogLevel.Debug);
loggerFactory.AddDebug();
app.UseOwinApp(owinApp =>
{
if (env.IsDevelopment())
{
owinApp.UseErrorPage(new ErrorPageOptions()
{
ShowCookies = true,
ShowEnvironment = true,
ShowExceptionDetails = true,
ShowHeaders = true,
ShowQuery = true,
ShowSourceCode = true
});
}
owinApp.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
HttpConfiguration config = new HttpConfiguration();
JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();
owinApp.UseCookieAuthentication(new CookieAuthenticationOptions());
owinApp.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "https://authentication.bl.at:5000",
RequiredScopes = new[] { "bl.API" },
//ValidationMode = ValidationMode.ValidationEndpoint,
//DelayLoadMetadata = true,
//// client credentials for the introspection endpoint
ClientId = "bl.API",
ClientSecret = "secret"
});
WebAPIConfig.Register(config);
ODataModelBuilder odataMetadataBuilder = new ODataConventionModelBuilder();
odataMetadataBuilder.EntitySet<Product>("Products");
config.MapODataServiceRoute(
routeName: "ODataRoute",
routePrefix: "odata",
model: odataMetadataBuilder.GetEdmModel());
owinApp.UseWebApi(config);
});
}
}
OwinExtensions.cs
public static class OwinExtensions
{
public static IApplicationBuilder UseOwinApp(this IApplicationBuilder aspNetCoreApp, Action<IAppBuilder> configuration)
{
return aspNetCoreApp.UseOwin(setup => setup(next =>
{
AppBuilder owinAppBuilder = new AppBuilder();
IApplicationLifetime aspNetCoreLifetime = (IApplicationLifetime)aspNetCoreApp.ApplicationServices.GetService(typeof(IApplicationLifetime));
AppProperties owinAppProperties = new AppProperties(owinAppBuilder.Properties);
owinAppProperties.OnAppDisposing = aspNetCoreLifetime?.ApplicationStopping ?? CancellationToken.None;
owinAppProperties.DefaultApp = next;
configuration(owinAppBuilder);
return owinAppBuilder.Build<Func<IDictionary<string, object>, Task>>();
}));
}
}
WebAPIConfig.cs
public class WebAPIConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
}
Exceptions
The WebAPI works as expected as long as oauth is disabled, when it's enabled it throws the following exception on startup:
Unbehandelte Ausnahme: System.NullReferenceException: Der Objektverweis wurde nicht auf eine Objektinstanz festgelegt.
bei IdentityServer3.AccessTokenValidation.DiscoveryDocumentIssuerSecurityTokenProvider..ctor(String discoveryEndpoint, IdentityServerBearerTokenAuthenticationOptions options, ILoggerFactory loggerFactory)
bei Owin.IdentityServerBearerTokenValidationAppBuilderExtensions.<>c__DisplayClass9.<ConfigureLocalValidation>b__8()
bei System.Lazy`1.CreateValue()
bei System.Lazy`1.LazyInitValue()
bei Owin.IdentityServerBearerTokenValidationAppBuilderExtensions.UseIdentityServerBearerTokenAuthentication(IAppBuilder app, IdentityServerBearerTokenAuthenticationOptions options)
bei WebAPI.Startup.<>c__DisplayClass1_0.<Configure>b__0(IAppBuilder owinApp) in C:\Users\User\Documents\visual studio 2015\Projects\TestProject\src\WebAPI\Startup.cs:Zeile 78.
bei WebAPI.Config.OwinExtensions.<>c__DisplayClass0_0.<UseOwinApp>b__1(Func`2 next) in C:\Users\User\Documents\visual studio 2015\Projects\TestProject\src\WebAPI\Config\OwinExtensions.cs:Zeile 29.
bei Microsoft.AspNetCore.Builder.OwinExtensions.<>c__DisplayClass0_1.<UseOwin>b__1(RequestDelegate next1)
bei Microsoft.AspNetCore.Builder.Internal.ApplicationBuilder.Build()
bei Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
bei Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
bei WebAPI.Program.Main(String[] args) in C:\Users\User\Documents\visual studio 2015\Projects\TestProject\src\WebAPI\Program.cs:Zeile 21.
I have also tried enabling delayLoadMetadata but this throws the following exception:
Unbehandelte Ausnahme: System.Reflection.TargetInvocationException: Ein Aufrufziel hat einen Ausnahmefehler verursacht. ---> System.NullReferenceException: Der Objektverweis wurde nicht auf eine Objektinstanz festgelegt.
bei IdentityServer3.AccessTokenValidation.IdentityServerBearerTokenValidationMiddleware..ctor(Func`2 next, IAppBuilder app, IdentityServerOAuthBearerAuthenticationOptions options, ILoggerFactory loggerFactory)
bei lambda_method(Closure , Func`2 , IAppBuilder , IdentityServerOAuthBearerAuthenticationOptions , ILoggerFactory )
--- Ende der internen Ausnahmestapelüberwachung ---
bei System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
bei System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
bei System.Delegate.DynamicInvokeImpl(Object[] args)
bei Microsoft.Owin.Builder.AppBuilder.BuildInternal(Type signature)
bei Microsoft.Owin.Builder.AppBuilderExtensions.Build[TApp](IAppBuilder builder)
bei WebAPI.Config.OwinExtensions.<>c__DisplayClass0_0.<UseOwinApp>b__1(Func`2 next) in C:\Users\User\Documents\visual studio 2015\Projects\TestProject\src\WebAPI\Config\OwinExtensions.cs:Zeile 31.
bei Microsoft.AspNetCore.Builder.OwinExtensions.<>c__DisplayClass0_1.<UseOwin>b__1(RequestDelegate next1)
bei Microsoft.AspNetCore.Builder.Internal.ApplicationBuilder.Build()
bei Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
bei Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
bei WebAPI.Program.Main(String[] args) in C:\Users\User\Documents\visual studio 2015\Projects\TestProject\src\WebAPI\Program.cs:Zeile 21.
I think this issue might be related to .Core/Owin dependency injection of ILoggerFactory. Might be a lifespan issue between these two?
Exceptions that you got before and after enabled DelayLoadMetadata are different, one is from constructor of DiscoveryDocumentIssuerSecurityTokenProvider while another is from constructor of IdentityServerBearerTokenValidationMiddleware
If you have a look at the implementation of UseIdentityServerBearerTokenAuthentication, you would see both modules depend on loggerFactory which gets from IApplicationBuilder by this line
var loggerFactory = app.GetLoggerFactory();
I am not a .net core expert, but the way how you use UseOwin extension method looks a bit strange to me, where you have a new instance of AppBuilder inside your owin pipeline instead of using the existing one - aspNetCoreApp, my guess is there is no logger factory registered with the new instance of AppBuilder, therefore when it is needed in modules in IdentityServer3, it blows up with object is null exception.
You can easily find out by setting a breakpoint before call into IdentityServerBearerTokenValidationMiddleware and manualy executes owinAppBuilder.GetLoggerFactory() in Immediate debug window to see if it returns anything
I run into the same issue, and i also tried it with the
DelayLoadMetadata = true option without any success.
To solve this problem i needed to set a default logger with app.SetLoggerFactory, before you call
app.UseIdentityServerBearerTokenAuthentication(GetOptions());
To do this you might need to ad
using Microsoft.Owin.Logging;
to your using’s and maybe add the assembly reference, this will add the SetLoggerFactory method to the app object. (it´s an extension).
In my case i´ve done it just with the default logger like this:
app.SetLoggerFactory(Microsoft.Owin.Logging.LoggerFactory.Default);
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
//some stuff
});
);

The type String cannot be constructed

I'm using Web.api and Unity and I am getting the following error when trying to open the default "help" area:
[InvalidOperationException: The type String cannot be constructed. You must configure the container to supply this value.]
Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.GuardTypeIsNonPrimitive(IBuilderContext context, SelectedConstructor selectedConstructor) +280
Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.PreBuildUp(IBuilderContext context) +356
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +260
Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlanCreatorPolicy.CreatePlan(IBuilderContext context, NamedTypeBuildKey buildKey) +205
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +231
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +260
Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey) +250
Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context) +101
BuildUp_System.Web.Http.HttpRouteCollection(IBuilderContext ) +202
Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context) +42
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +319
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +260
Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey) +250
Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context) +101
BuildUp_System.Web.Http.HttpConfiguration(IBuilderContext ) +202
Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context) +42
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +319
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +260
Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey) +250
Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context) +101
BuildUp_API.Areas.HelpPage.Controllers.HelpController(IBuilderContext ) +204
Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context) +42
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +319
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +260
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides) +373
[ResolutionFailedException: Resolution of the dependency failed, type = "API.Areas.HelpPage.Controllers.HelpController", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type String cannot be constructed. You must configure the container to supply this value.
-----------------------------------------------
At the time of the exception, the container was:
Resolving API.Areas.HelpPage.Controllers.HelpController,(none)
Resolving parameter "config" of constructor API.Areas.HelpPage.Controllers.HelpController(System.Web.Http.HttpConfiguration config)
Resolving System.Web.Http.HttpConfiguration,(none)
Resolving parameter "routes" of constructor System.Web.Http.HttpConfiguration(System.Web.Http.HttpRouteCollection routes)
Resolving System.Web.Http.HttpRouteCollection,(none)
Resolving parameter "virtualPathRoot" of constructor System.Web.Http.HttpRouteCollection(System.String virtualPathRoot)
Resolving System.String,(none)
]
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides) +436
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, String name, IEnumerable`1 resolverOverrides) +50
Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides) +48
Microsoft.Practices.Unity.UnityContainerExtensions.Resolve(IUnityContainer container, Type t, ResolverOverride[] overrides) +61
Unity.Mvc4.UnityDependencyResolver.GetService(Type serviceType) +140
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +87
[InvalidOperationException: An error occurred when trying to create a controller of type 'API.Areas.HelpPage.Controllers.HelpController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +247
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +438
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +226
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +326
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +177
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +88
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +50
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
I am new to unity and am sure I am missing step(s).
In webapiconfig.cs:
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//Custom formatter
config.Formatters.Clear();
config.Formatters.Add(new JSONPFormater());
config.EnableSystemDiagnosticsTracing();
//Setup DI
Bootstrapper.Initialise();
}
Bootstraper.cs(default values)
public static class Bootstrapper
{
public static IUnityContainer Initialise()
{
var container = BuildUnityContainer();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
return container;
}
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
RegisterTypes(container);
return container;
}
public static void RegisterTypes(IUnityContainer container)
{
}
}
My attempt at a web.config
web.config
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
</configSections>
<connectionStrings>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-API-20130708152001;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-API-20130708152001.mdf" />
<add name="<REMOVED>DBEntities" connectionString="metadata=res://*/Models.DAL.<REMOVED>.csdl|res://*/Models.DAL.<REMOVED>.ssdl|res://*/Models.DAL.<REMOVED>.msl;provider=System.Data.SqlClient;provider connection string="data source=<REMOVED>;initial catalog=<REMOVED>;persist security info=True;user id=<REMOVED>;password=<REMOVED>;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<!--unity setting-->
<unity>
<containers>
<types>
<register type="API.Areas.HelpPage.Controllers.HelpController, API">
<constructor>
<param valu=""></param>
</constructor>
</register>
</types>
</containers>
</unity>
Am I headed in the right direction??
Thanks
Update:
helpcontroller.cs:
public class HelpController : Controller
{
public HelpController()
: this(GlobalConfiguration.Configuration)
{
}
public HelpController(HttpConfiguration config)
{
Configuration = config;
}
public HttpConfiguration Configuration { get; private set; }
public ActionResult Index()
{
return View(Configuration.Services.GetApiExplorer().ApiDescriptions);
}
public ActionResult Api(string apiId)
{
if (!String.IsNullOrEmpty(apiId))
{
HelpPageApiModel apiModel = Configuration.GetHelpPageApiModel(apiId);
if (apiModel != null)
{
return View(apiModel);
}
}
return View("Error");
}
}
url I am trying to access: http:// hostname:port/Help
I think a better way is to add InjectionConstructor attribute to the default constructor. This attribute forces unity to use the decorated constructor.
Example:
public class HelpController : Controller
{
private const string ErrorViewName = "Error";
[InjectionConstructor]
public HelpController()
: this(GlobalConfiguration.Configuration)
{
}
As your code sample, I'm assuming you are on a Controller and not a API Controller (from web api).
Your api controller has a dependency on the constructor from HttpConfiguration. The container problably does not have this definition for this type and consequently does not know how to solve it and the string on the error message should come from this type as a dependency. I recommend you use the GlobalConfiguration static class and access the Configuration property to get a HttpConfiguration instance. You could abstract it in a property, for sample:
// include this namespace
using System.Web.Http;
public class HelpController : Controller
{
// remove the constructors...
// property
protected static HttpConfiguration Configuration
{
get { return GlobalConfiguration.Configuration; }
}
public ActionResult Index()
{
return View(this.Configuration.Services.GetApiExplorer().ApiDescriptions);
}
public ActionResult Api(string apiId)
{
if (!String.IsNullOrEmpty(apiId))
{
HelpPageApiModel apiModel = this.Configuration.GetHelpPageApiModel(apiId);
if (apiModel != null)
{
return View(apiModel);
}
}
return View("Error");
}
}
Now, if you are on a Api Controller, you just can access directly the this.Configuration property that is already on the ApiController (base class for Api controllers) and get a instance of HttpConfiguration.
The reason this happens is because Unity will by default choose to use the constructor with the most parameters thus bypassing the default constructor.
Comment out the two constructors that exist in the HelpController template and add a default one that sets the configuration.
//public HelpController()
// : this(GlobalConfiguration.Configuration)
//{
//}
//public HelpController(HttpConfiguration config)
//{
// Configuration = config;
//}
public HelpController()
{
Configuration = GlobalConfiguration.Configuration;
}
Registering the HttpConfiguration object as an instance in UnityContainer will also help resolve the issue.
Just need to add to add the below line while registering in UnityContainer.
public static void RegisterTypes(IUnityContainer container) {
container.RegisterInstance<HttpConfiguration>(GlobalConfiguration.Configuration);
}
This will help Unity resolve the config parameter, when it invokes the constructor with the parameter.
public HelpController(HttpConfiguration config) {
Configuration = config;
}
I've recently had this error happen on a previously working codebase. The following answer shows what I did to correct it:
Adding Web API and API documentation to an existing MVC project
Basically make the constructor with parameters protected rather than public

Resources