I've been hovering around this issue for quite some time now and still haven't found an answer, nor another post dealing with the same problem.
I have published a .net 5.0 Website and everything works fine if I run dotnet inside the same published folder. in this folder I also have a file called appsettings.json with all the configuration needed by the application ie:
+ path
+ to
+ karinapi
- MinosIT.Karin.API.dll
- appsettings.json
When I run dotnet inside the folder, everything works fine and the settings are read without any problem:
cd /path/to/karinapi
dotnet MinosIT.Karin.API.dll
The result is ok ie:
user#machine$ dotnet MinosIT.Karin.API.dll
info: MinosIT.Karin.API.Program[0]
Inicializando migraciĆ³n
info: MinosIT.Karin.Migrations.HDIKarinMigrations[0]
Verificando migraci+on
info: MinosIT.Karin.Migrations.HDIKarinMigrations[0]
Checking whether journal table exists..
info: MinosIT.Karin.Migrations.HDIKarinMigrations[0]
Fetching list of already executed scripts.
info: MinosIT.Karin.API.Program[0]
finalizando migraciĆ³n
but when I try to follow this guide:
https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/linux-nginx?view=aspnetcore-5.0
it says that you have to create a service and run the app like this
/usr/bin/dotnet /path/to/karinapi/MinosIT.Karin.API.dll
The problem is that when I try to run my app while being outside the publish folder, dotnet doesn't seem to find appsettings.json file ie:
user#mymachine$ pwd
/path/to/
user#mymachine$ /user/bin/dotnet /path/to/karinapi/MinosIT.Karin.API.dll
Application fails and throws this error:
user#mymachine$ dotnet karinapi/MinosIT.Karin.API.dll
Unhandled exception. System.ArgumentNullException: Value cannot be null. (Parameter 'implementationInstance')
at Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions.AddSingleton[TService](IServiceCollection services, TService implementationInstance)
at MinosIT.Karin.API.Startup.ConfigureServices(IServiceCollection services) in D:\Minos IT\Karin\MinosIT.Karin\BackEnd\MinosIT.Karin.api\Startup.cs:line 72
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) in /_/src/coreclr/src/System.Private.CoreLib/src/System/Reflection/RuntimeMethodInfo.cs:line 399
at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.InvokeCore(Object instance, IServiceCollection services)
at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.<>c__DisplayClass9_0.g__Startup|0(IServiceCollection serviceCollection)
at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.Invoke(Object instance, IServiceCollection services)
at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.<>c__DisplayClass8_0.b__0(IServiceCollection services)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.UseStartup(Type startupType, HostBuilderContext context, IServiceCollection services, Object instance)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass13_0.b__0(HostBuilderContext context, IServiceCollection services)
at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
at Microsoft.Extensions.Hosting.HostBuilder.Build()
I'm using Microsoft.Extensions.Configuration.
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
public IConfiguration Configuration { get; }
...
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
and inside StartUp.ConfigureServices I'm using:
var connectionString = Configuration.GetConnectionString("ConnectionStringName");
var section = Configuration.GetSection("CustomSection").Get<CustomConfiguration>();
When I debug, my code via logging I understand that the problem might be the ASP.NET Core doesn't know where to read appsettings.json, I have looked at dotnet cli docs, environment variables, other configuration types and I can't seem to find the problem. I really don't know what else to look for, any guidance or help will be appreciated.
Thanks in advance for your help.
Found a solution, I'm posting here in case someone else is struggling with the same error:
inside Program.cs I changed from:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
}
);
to
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, config) =>
{
var assembly = Assembly.GetExecutingAssembly();
var currentPath = System.IO.Path.GetDirectoryName(assembly.Location);
config.SetBasePath(currentPath);
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
}
);
Related
My program.cs file in .NET Core 3.1 is like this I am creating web API in .net core but I am getting this error when hosted on server in IIS. API is working fine when hosted locally.
public class Program
{
public static void Main(string[] args)
{
var logger = NLogBuilder.ConfigureNLog(String.Concat(Directory.GetCurrentDirectory(), "/nlog.config")).GetLogger();
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
}).ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
})
.UseNLog();
}
System.OperationCanceledException: at program.cs error
I am getting this error with stack trace like:
Description: The process was terminated due to an unhandled exception.
Exception Info: System.OperationCanceledException: The operation was canceled.
at System.Threading.CancellationToken.ThrowOperationCanceledException()
at System.Threading.CancellationToken.ThrowIfCancellationRequested()
at Microsoft.Extensions.Hosting.Internal.Host.StopAsync(CancellationToken
cancellationToken)
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.WaitForShutdownAsync(IHost
host, CancellationToken token)
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost
host, CancellationToken token)
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.RunAsync(IHost
host, CancellationToken token)
at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost
host)
What is wrong here?
I am experiencing the same error, and I was trying to see what might cause it.
I came across this link with the same issue
and the thing that jumped out at me was the "non-graceful shutdown". To test, I recycled the application website on IIS, which did not trigger the error. I then tried turning off the app pool via IIS, and DID trigger the exception.
This leads me to believe it has something to do with a task running inside the application that is cut short when the non-graceful shutdown occurs.
In my case, I have a HostedService running in the background of my application, do you have something similar in yours?
I am trying to script/export Entity Framework Core code-first migrations in Azure DevOps CI pipeline but having an error. The below command runs fine in my Visual Studio locally and generates an sql file and the command work was also working fine a few months ago in DevOps too (not sure if update related).
dotnet ef migrations script --project Booking.Core
--startup-project Booking.Management --idempotent
--output $(build.artifactstagingdirectory)/migrate.sql --verbose
My project is using .NET Core 3.1.5 version and also in pipeline I make sure dotnet-ef command is available like
dotnet tool install --global dotnet-ef --version 3.1.5
But I still keep getting this error:
2020-12-13T09:13:27.8973893Z ##[section]Starting: EF Core Migrations SQL Export
2020-12-13T09:13:27.9112206Z ==============================================================================
2020-12-13T09:13:27.9112480Z Task : PowerShell
2020-12-13T09:13:27.9112737Z Description : Run a PowerShell script on Linux, macOS, or Windows
2020-12-13T09:13:27.9112956Z Version : 2.179.1
2020-12-13T09:13:27.9113144Z Author : Microsoft Corporation
2020-12-13T09:13:27.9113446Z Help : https://learn.microsoft.com/azure/devops/pipelines/tasks/utility/powershell
2020-12-13T09:13:27.9113759Z ==============================================================================
2020-12-13T09:13:28.8144250Z Generating script.
2020-12-13T09:13:28.8694723Z ========================== Starting Command Output ===========================
2020-12-13T09:13:28.8987598Z ##[command]"C:\windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'D:\a\_temp\fa82967e-1e57-4dba-932d-1453e98ef510.ps1'"
2020-12-13T09:13:29.4639310Z Using project 'Booking.Core\Booking.Core.csproj'.
2020-12-13T09:13:29.4640261Z Using startup project 'Booking.Management\Booking.Management.csproj'.
2020-12-13T09:13:29.4661731Z Writing 'Booking.Core\obj\Booking.Core.csproj.EntityFrameworkCore.targets'...
2020-12-13T09:13:29.4713085Z dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=C:\Users\VssAdministrator\AppData\Local\Temp\tmpBC2B.tmp /verbosity:quiet /nologo Booking.Core\Booking.Core.csproj
2020-12-13T09:13:30.5894726Z Writing 'Booking.Management\obj\Booking.Management.csproj.EntityFrameworkCore.targets'...
2020-12-13T09:13:30.5904170Z dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=C:\Users\VssAdministrator\AppData\Local\Temp\tmpC091.tmp /verbosity:quiet /nologo Booking.Management\Booking.Management.csproj
2020-12-13T09:13:31.4844212Z Build started...
2020-12-13T09:13:31.4848105Z dotnet build Booking.Management\Booking.Management.csproj /verbosity:quiet /nologo
2020-12-13T09:13:39.4566730Z
2020-12-13T09:13:39.4680169Z Build succeeded.
2020-12-13T09:13:39.4681347Z 0 Warning(s)
2020-12-13T09:13:39.4681964Z 0 Error(s)
2020-12-13T09:13:39.4682460Z
2020-12-13T09:13:39.4683029Z Time Elapsed 00:00:07.53
2020-12-13T09:13:39.5195940Z Build succeeded.
2020-12-13T09:13:39.5465861Z dotnet exec --depsfile D:\a\1\s\Booking.Management\bin\Debug\netcoreapp3.1\Booking.Management.deps.json --additionalprobingpath C:\Users\VssAdministrator\.nuget\packages --additionalprobingpath "C:\Program Files\dotnet\sdk\NuGetFallbackFolder" --runtimeconfig D:\a\1\s\Booking.Management\bin\Debug\netcoreapp3.1\Booking.Management.runtimeconfig.json C:\Users\VssAdministrator\.dotnet\tools\.store\dotnet-ef\3.1.5\dotnet-ef\3.1.5\tools\netcoreapp3.1\any\tools\netcoreapp2.0\any\ef.dll migrations script --idempotent --output D:\a\1\a/migrate.sql --assembly D:\a\1\s\Booking.Management\bin\Debug\netcoreapp3.1\Booking.Core.dll --startup-assembly D:\a\1\s\Booking.Management\bin\Debug\netcoreapp3.1\Booking.Management.dll --project-dir D:\a\1\s\Booking.Core\ --language C# --working-dir D:\a\1\s --verbose --root-namespace Booking.Core
2020-12-13T09:13:39.7619178Z Using assembly 'Booking.Core'.
2020-12-13T09:13:39.7621486Z Using startup assembly 'Booking.Management'.
2020-12-13T09:13:39.7623162Z Using application base 'D:\a\1\s\Booking.Management\bin\Debug\netcoreapp3.1'.
2020-12-13T09:13:39.7624489Z Using working directory 'D:\a\1\s\Booking.Management'.
2020-12-13T09:13:39.7627735Z Using root namespace 'Booking.Core'.
2020-12-13T09:13:39.7628656Z Using project directory 'D:\a\1\s\Booking.Core\'.
2020-12-13T09:13:40.0447318Z Finding DbContext classes...
2020-12-13T09:13:40.0448237Z Finding IDesignTimeDbContextFactory implementations...
2020-12-13T09:13:40.1345335Z Finding application service provider...
2020-12-13T09:13:40.1352141Z Finding Microsoft.Extensions.Hosting service provider...
2020-12-13T09:13:40.1387349Z Using environment 'Development'.
2020-12-13T09:13:41.3123215Z Rollbar.RollbarException: Failed to configure using invalid configuration prototype!
2020-12-13T09:13:41.3123976Z at Rollbar.RollbarLogger.ValidateConfiguration(IRollbarConfig rollbarConfig)
2020-12-13T09:13:41.3124504Z at Rollbar.RollbarLogger.Configure(IRollbarConfig settings)
2020-12-13T09:13:41.3125776Z at Rollbar.RollbarLogger.Rollbar.IRollbar.Configure(IRollbarConfig settings)
2020-12-13T09:13:41.3127983Z at Booking.Management.Startup.ConfigureServices(IServiceCollection services) in D:\a\1\s\Booking.Management\Startup.cs:line 136
2020-12-13T09:13:41.3128521Z at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
2020-12-13T09:13:41.3129014Z at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
2020-12-13T09:13:41.3129472Z at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.InvokeCore(Object instance, IServiceCollection services)
2020-12-13T09:13:41.3129921Z at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.<>c__DisplayClass9_0.<Invoke>g__Startup|0(IServiceCollection serviceCollection)
2020-12-13T09:13:41.3130590Z at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.Invoke(Object instance, IServiceCollection services)
2020-12-13T09:13:41.3131087Z at Microsoft.AspNetCore.Hosting.ConfigureServicesBuilder.<>c__DisplayClass8_0.<Build>b__0(IServiceCollection services)
2020-12-13T09:13:41.3131685Z at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.UseStartup(Type startupType, HostBuilderContext context, IServiceCollection services)
2020-12-13T09:13:41.3132193Z at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.<>c__DisplayClass12_0.<UseStartup>b__0(HostBuilderContext context, IServiceCollection services)
2020-12-13T09:13:41.3132570Z at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
2020-12-13T09:13:41.3132842Z at Microsoft.Extensions.Hosting.HostBuilder.Build()
2020-12-13T09:13:41.3133338Z An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: Failed to configure using invalid configuration prototype!
2020-12-13T09:13:41.3133808Z No application service provider was found.
2020-12-13T09:13:41.3309579Z Finding DbContext classes in the project...
2020-12-13T09:13:41.3402462Z Found DbContext 'ApplicationDbContext'.
2020-12-13T09:13:41.3673060Z Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
2020-12-13T09:13:41.3674225Z ---> System.MissingMethodException: No parameterless constructor defined for type 'Booking.Core.Data.ApplicationDbContext'.
2020-12-13T09:13:41.3674932Z at System.RuntimeType.CreateInstanceDefaultCtorSlow(Boolean publicOnly, Boolean wrapExceptions, Boolean fillCache)
2020-12-13T09:13:41.3675640Z at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, Boolean wrapExceptions)
2020-12-13T09:13:41.3676267Z at System.Activator.CreateInstance(Type type, Boolean nonPublic, Boolean wrapExceptions)
2020-12-13T09:13:41.3676691Z at System.Activator.CreateInstance(Type type)
2020-12-13T09:13:41.3677358Z at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_3.<FindContextTypes>b__13()
2020-12-13T09:13:41.3677798Z --- End of inner exception stack trace ---
2020-12-13T09:13:41.3678247Z at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.<>c__DisplayClass13_3.<FindContextTypes>b__13()
2020-12-13T09:13:41.3678609Z at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
2020-12-13T09:13:41.3678993Z at Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
2020-12-13T09:13:41.3681847Z at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.ScriptMigration(String fromMigration, String toMigration, Boolean idempotent, String contextType)
2020-12-13T09:13:41.3682773Z at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScriptMigrationImpl(String fromMigration, String toMigration, Boolean idempotent, String contextType)
2020-12-13T09:13:41.3683262Z at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScriptMigration.<>c__DisplayClass0_0.<.ctor>b__0()
2020-12-13T09:13:41.3683647Z at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0()
2020-12-13T09:13:41.3684014Z at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
2020-12-13T09:13:41.3684531Z Unable to create an object of type 'ApplicationDbContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
2020-12-13T09:13:41.6277035Z ##[error]PowerShell exited with code '1'.
2020-12-13T09:13:41.6727543Z ##[section]Finishing: EF Core Migrations SQL Export
My Program.cs file looks like this:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
My ApplicationDbContext has constructors like:
protected ApplicationDbContext() {}
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, IHttpContextAccessor contextAccessor) : base(options)
{
_contextAccessor = contextAccessor;
}
My Startup.cs file looks like:
public Startup(IWebHostEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)standard environment name (e.g: Local).
.AddUserSecrets<Startup>()
.AddEnvironmentVariables();
Configuration = builder.Build();
Environment = env;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<User, Role>(
config => {...})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders()
.AddUserValidator<IdendityUserValidator<User>>();
}
Rollbar configuration was failing because for access token it was expecting a string that was not null/empty. Since I store Rollbar access token in Azure AppService Configuration and appsettings.json did not have access token listed, error was happening. So I added access token to appsettings.json with a dummy non-empty string value. That helps Rollbar to configure itself and not fail.
I am running an ASP.NET Core web app and want to upload large files.
I know that when running IIS, the limits can be changed via web.config:
<httpRuntime maxRequestLength="1048576" />
...
<requestLimits maxAllowedContentLength="1073741824" />
How can you do the equivalent while running the new ASP.NET Core Kestrel web server?
I get the exception "Request body too large."
I found this helpful announcement that confirms there is a 28.6 MB body size limit starting with ASP.NET Core 2.0, but more importantly shows how to get around it!
To summarize:
For a single controller or action, use the [DisableRequestSizeLimit] attribute to have no limit, or the [RequestSizeLimit(100_000_000)] to specify a custom limit.
To change it globally, inside of the BuildWebHost() method, inside the Program.cs file, add the .UseKestrel option below:
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseKestrel(options =>
{
options.Limits.MaxRequestBodySize = null;
}
For additional clarity, you can also refer to the Kestrel options documentation.
The other answer is for ASP.NET Core 2.0, but I would like to provide the solution for .NET Core 3.x web API.
Your code in program.cs must be like this to work:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseKestrel(options =>
{
options.Limits.MaxRequestBodySize = null;
});
});
}
I am running an ASP.NET Core web app and want to upload large files.
I know that when running IIS, the limits can be changed via web.config:
<httpRuntime maxRequestLength="1048576" />
...
<requestLimits maxAllowedContentLength="1073741824" />
How can you do the equivalent while running the new ASP.NET Core Kestrel web server?
I get the exception "Request body too large."
I found this helpful announcement that confirms there is a 28.6 MB body size limit starting with ASP.NET Core 2.0, but more importantly shows how to get around it!
To summarize:
For a single controller or action, use the [DisableRequestSizeLimit] attribute to have no limit, or the [RequestSizeLimit(100_000_000)] to specify a custom limit.
To change it globally, inside of the BuildWebHost() method, inside the Program.cs file, add the .UseKestrel option below:
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseKestrel(options =>
{
options.Limits.MaxRequestBodySize = null;
}
For additional clarity, you can also refer to the Kestrel options documentation.
The other answer is for ASP.NET Core 2.0, but I would like to provide the solution for .NET Core 3.x web API.
Your code in program.cs must be like this to work:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseKestrel(options =>
{
options.Limits.MaxRequestBodySize = null;
});
});
}
No matter when or where I set either ASPNET_ENV or Hosting:Environment the startup code will always enter
//This method is invoked when ASPNET_ENV is 'Production'
//The allowed values are Development,Staging and Production
public void ConfigureProduction(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(minLevel: LogLevel.Warning);
Configure(app);
}
What I've tried so far
Set Hosting:Environment to Development in the project properties
Set ASPNET_ENV to Development in the project properties
Set Hosting:Environment to Development in launchSettings.json
Set ASPNET_ENV to Development in launchSettings.json
Set ASPNET_ENV to Development in code via Environment.SetEnvironmentVariable("ASPNET_ENV", "Development"); in the Startup method before the call to ConfigurationBuilder.GetEnvironmentVariables()
This is version 1.0.0-rc2-20143 by the way. Am I missing something here or is it just a bug?
The environment variable name has been changed to ASPNETCORE_ENVIRONMENT as part of the name change.
It was announced in this issue and change in this PR.
If you have not done it already, try adding the environment variables to the configuration instance.
public static void Main(string[] args)
{
var builder = new ConfigurationBuilder();
builder.AddJsonFile("appsettings.json");
builder.AddEnvironmentVariables();
var config = builder.Build();
}
Whilst the answer from Henk Mollema is correct for the environment variable name, I still encountered issues where dotnetcore would seem to ignore the environment variable and use appsettings.json when run from command line.
To ensure it uses the correct environment and app settings, try the following:
Change the environment variable via Project Properties -> Debug -> Environment Variables -> ASPNETCORE_ENVIRONMENT -> Value : Change the value to match your intended environment eg Staging
Build Solution
From commandline, type SETX ASPNETCORE_ENVIRONMENT "YOUR-ENVIRONMENT-NAME" where replace "YOUR-ENVIRONMENT-NAME" to match what you set in step 1 eg Staging and ensure you include the "quotes"
IMPORTANT - make sure you all your various appsettings.json eg appsettings.staging.json is present in the project directory where you will run it. (In the case of a published solution, the appsettings.staging.json may not have been copied, so ensure it's there)
From Commandline, go to your project directory (or published directory) and run your project by typing dotnet run (or "dotnet YOURPROJECTNAME.DLL" for published projects)
Observe in the next line that appears in the commandline which states Hosting environment: YOURENVIRONMENTNAME eg Hosting environment:staging
Running a DotNetCore project from Visual Studio always picked the
correct appsettings based on the environment set in your project
properties, however these are the steps I followed to run dotnet core correctly from commandline
working correctly.
This worked for me using .net core 2.0 and building a web api. Notice the 2 different methods of accessing the environment variable.
Program.cs
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args){
if(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT ") == "Production"){
return WebHost.CreateDefaultBuilder(args)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
} else {
return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}
But in the startup file there is another environment option
Startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()));
var connectionString = "Data Source=tcp:<some-ip>,<some-port>;Initial Catalog=<some database>;Integrated Security=False;User Id=SA;Password=<some password>;MultipleActiveResultSets=True";
services.AddDbContext<myContext>(opt => opt.UseSqlServer(connectionString));
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors("AllowAll");
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}