I have migrated our application from .NET Core 2.2 to version 3.0. Actually I created the new application in 3.0 from scratch and then copied source code files. Everything looks great but when I try to run the application within Visual Studio 2019 I get the exception:
Application is running inside IIS process but is not configured to use IIS server
Here is my Program.cs
public static class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseContentRoot(Directory.GetCurrentDirectory());
webBuilder.UseKestrel();
webBuilder.UseIISIntegration();
webBuilder.UseStartup<Startup>();
});
}
The error occurs at the line: CreateHostBuilder(args).Build().Run();
It worked fine in .NET Core 2.2 but it doesn’t want to run as 3.0. I cannot find anything else that should be done. Something new in the Startup.cs? I don’t know.
asked Sep 24, 2019 at 12:28
Ondrej VencovskyOndrej Vencovsky
2,9089 gold badges28 silver badges34 bronze badges
2
I also came across this issue while following the documentation https://learn.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.0&tabs=visual-studio
For your case I have checked and the code below will work, with the call to webBuilder.UseKestrel() removed.
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseContentRoot(Directory.GetCurrentDirectory());
webBuilder.UseIISIntegration();
webBuilder.UseStartup<Startup>();
});
![]()
answered Sep 25, 2019 at 6:14
![]()
7
I had the same error then to fix my problem I needed to change webBuilder.UseKestrel(); to ConfigureKestrel(serverOptions => {})
My Program.cs before:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseKestrel();
webBuilder.UseStartup<Startup>();
});
My Program.cs fixed:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureKestrel(serverOptions =>
{
})
.UseStartup<Startup>();
});
answered Aug 20, 2020 at 13:11
![]()
0
In my case I ran wrong profile (IIS Express) in Visual Studio by carelessness.

answered Feb 28, 2020 at 8:52
flam3flam3
1,7791 gold badge17 silver badges26 bronze badges
As @flam3 suggested, you need to select a profile with correct command.
Open Solution Explorer -> Your Project Name -> Properties -> launchSettings.json file.
The value of the key commandName should be ‘Project’ instead of ‘IIS Express’
So select profile with the name Elsa.Samples.UserRegistration.Web(in my case). See below. Or you may try changing IISExpress to Project on line no 19

answered Mar 29, 2021 at 8:21
VivekDevVivekDev
17.7k22 gold badges116 silver badges178 bronze badges
For Visual Studio 2019 and 2022
Go to API project properties: Debug Tab -> General -> Hit «Open Debug launch profiles UI»

Scroll Down to Hosting Model and Select «Out Of process»

Then, you will be able to run your application with no Issues.
answered Feb 14, 2022 at 17:10
![]()
David CastroDavid Castro
1,66321 silver badges19 bronze badges
0
Запуск приложения. Класс Program
Данное руководство устарело. Актуальное руководство: Руководство по ASP.NET Core 7
Последнее обновление: 29.10.2019
В любом типе проектов ASP.NET Core, как и в проекте консольного приложения, мы можем найти файл Program.cs, в котором определен одноименный класс Program
и с которого по сути начинается выполнение приложения. В ASP.NET Core 3 этот файл выглядит следующим образом:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace HelloApp
{
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>();
});
}
}
Чтобы запустить приложение ASP.NET Core, необходим объект IHost, в рамках которого развертывается веб-приложение. Для
создания IHost применяется объект IHostBuilder.
В программе по умолчанию в статическом методе CreateHostBuilder как раз создается и настраивается IHostBuilder.
Непосредственно создание IHostBuilder производится с помощью метода Host.CreateDefaultBuilder(args).
Данный метод выполняет ряд задач.
-
Устанавливает корневой каталог (для этого используется свойство Directory.GetCurrentDirectory). Корневой каталог представляет папку, где будет
производиться поиск различного содержимого, например, представлений. -
Устанавливает конфигурацию хоста. Для этого загружаются переменные среды с префиксом «DOTNET_» и аргументы командной строки
-
Устанавливает конфигурацию приложения. Для этого загружается содержимое из файлов appsettings.json и appsettings.{Environment}.json, а также
переменные среды и аргументы командной строки. Если приложение в статусе разработки, то также используются данные Secret Manager (менеджера секретов), который
позволяет сохранить конфиденциальные данные, используемые при разработке. -
Добавляет провайдеры логирования
-
Если проект в статусе разработки, то также обеспечивает валидацию сервисов
Далее вызывается метод ConfigureWebHostDefaults(). Этот метод призван выполнять конфигурацию параметров хоста, а именно:
-
Загружает конфигурацию из переменных среды с префиксом «ASPNETCORE_»
-
Запускает и настраивает веб-сервер Kestrel, в рамках которого будет разворачиваться приложение
-
Добавляет компонент
Host Filtering, который позволяет настраивать адреса для веб-сервера Kestrel -
Если переменная окружения
ASPNETCORE_FORWARDEDHEADERS_ENABLEDравнаtrue, добавляет компонент Forwarded Headers, который позволяет считывать из запроса заголовки «X-Forwarded-« -
Если для работы приложения требуется IIS, то данный метод также обеспечивает интеграцию с IIS
Метод ConfigureWebHostDefaults() в качестве параметра принимает делегат Action<IWebHostBuilder&.
А помощью последовательного вызова цепочки методов у объекта IWebHostBuilder производится инициализация веб-сервера для развертывания
веб-приложения. В частности, в данном случае у IWebHostBuilder вызывается метод UseStartup():
webBuilder.UseStartup<Startup>()
Этим вызовом устанавливается стартовый класс приложения — класс Startup, с которого и будет начинаться обработка входящих запросов.
В методе Main вызывается метод у созданного объекта IHostBuilder вызывается метод Build(), который собственно создает хост — объект IHost, в рамках которого
развертывается веб-приложение. А затем для непосредственного запуска у IHost вызывается метод Run:
CreateHostBuilder(args).Build().Run();
После этого приложение запущено, и веб-сервер начинает прослушивать все входящие HTTP-запросы.
- Remove From My Forums
-
Question
-
User-1355965324 posted
System.AggregateException: ‘Some services are not able to be constructed (Error while validating the service descriptor ‘ServiceType in program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace MyWeather { 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 code is given below
Interface using MyWeather.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MyWeather.Repository.IRepository { public interface IWeatherRepository { Task<IEnumerable<Weather>> GetWeatherAsync(); } } Repo using MyWeather.Models; using MyWeather.Repository.IRepository; using MyWeather.Utility; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace MyWeather.Repository { public class WeatherRepository : IWeatherRepository { private readonly IHttpClientFactory _clientFactory; public WeatherRepository(IHttpClientFactory clientFactory) { _clientFactory = clientFactory; } public async Task<IEnumerable<Weather>> GetWeatherAsync() { var url = SD.APILocationUrl; var request = new HttpRequestMessage(HttpMethod.Get, url); var client = _clientFactory.CreateClient(); HttpResponseMessage response = await client.SendAsync(request); IEnumerable<Weather> weather = new List<Weather>(); if (response.StatusCode == System.Net.HttpStatusCode.OK) { var jsonString = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<IEnumerable<Weather>>(jsonString); } return null; } } } startup.cs public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection"))); services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<ApplicationDbContext>(); services.AddScoped<IUnitOfWork,UnitOfWork>(); services.AddScoped<IWeatherRepository, WeatherRepository>(); services.AddControllersWithViews().AddRazorRuntimeCompilation(); services.AddRazorPages(); } Controller using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using MyWeather.Models; using MyWeather.Repository.IRepository; using Microsoft.AspNetCore.Mvc; namespace MyWeather.Areas.Customer.Controllers { [Area("Customer")] public class ForcastController : Controller { private readonly IWeatherRepository _weatherRepository; public Weather Weather { get; set; } public ForcastController(IWeatherRepository weatherRepository) { _weatherRepository = weatherRepository; } public async Task<IActionResult> Index() { var Weather = new List<Weather>(); var weatherList = await _weatherRepository.GetWeatherAsync(); return View(); } } }Weather.Repository.IRepository.IWeatherRepository Lifetime: Scoped ImplementationType:
My code
Answers
-
User-1355965324 posted
sorry I forgot to add the line in startup
services.AddHttpClient();
-
Marked as answer by
Thursday, October 7, 2021 12:00 AM
-
Marked as answer by
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Labels
area-runtime
Includes: Azure, Caching, Hosting, Middleware, Websockets, Kestrel, IIS, ANCM, HttpAbstractions
feature-hosting
Includes: Hosting
Comments
Environment=ASPNETCORE_URLS=http://localhost:5001
It is not working for ASP.NET CORE 3.0 on Linux. How to fix?
@justlearntutors Thanks for contacting us.
Can you provide more details on what you are doing?
Are you on plain Linux or inside a container?
Are you running the app with dotnet run? Check that you don’t have a launchSettings.json file under /Properties if that’s the case. It will override the ASPNETCORE_URLS environment variable.
@Tratcher can you assist here?
Can you provide more details on what you are doing?
Running 2 websites on Linux Ubuntu 18
Are you on plain Linux or inside a container?
Plain Linux
Are you running the app with dotnet run?
No, we use .service file
Check that you don’t have a launchSettings.json file under /Properties if that’s the case. It will override the ASPNETCORE_URLS environment variable.
We have launchSettings.json file under /Properties.
«applicationUrl»: «http://localhost:5001;http://localhost:5000»,
Environment=ASPNETCORE_URLS=http://localhost:5001 is invalid input, where did you see that?
The environment variables should be:
ASPNETCORE_ENVIRONMENT=Development
ASPNETCORE_URLS=http://localhost:5000
Also, why did you change port 5001 from https to http? If you don’t plan to use https then remove the 5001 entry and use 5000 instead.
Closing this as we haven’t heard from you and generally close issues with no response after some time. Please feel free to comment if you’re able to get the information we’re looking for and we can reopen the issue to investigate further!
Hi @Tratcher ,
That’s how you can specify environment variables in systemd service definition.
Example configuration is
[Unit]
Description=eventpublisher service
After=network.target
[Service]
WorkingDirectory=/home/0.0.0.24
User=build-integration
Group=build-integration
ExecStart=/home/0.0.0.24/Events.Api
Restart=always
RestartSec=10
SyslogIdentifier=eventpublisher
Environment=ASPNETCORE_ENVIRONMENT=qa
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false
Environment=ASPNETCORE_URLS=http://0.0.0.0:55471
[Install]
WantedBy=multi-user.target
The issue is that starting from NetCore 3.0 ASPNETCORE_URLS under linux are not picked up atumatically, and webservice always tries to start under localhost:5000
I have the same issue. Exactly same configuration, but for 2.1 works good.
Thanks,
Stas
Update. Using NetCore 3.0
Don’t pickup ASPNETCORE_URLS :
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>();
});
}
Works
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
That’s interesting because the config is handled similarly between them.
First we need to confirm if the environment variables were never picked up or if they were overwritten by something else. Try this:
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
var config = host.Services.GetRequiredService<IConfiguration>();
foreach (var c in config.AsEnumerable())
{
Console.WriteLine(c.Key + " = " + c.Value);
}
}
You should get both «URLS» and «ASPNETCORE_URLS» with the same value. Similarly for ENVIRONMENT.
Hi @Tratcher ,
I can reproduce that locally on my dev environment (Ubuntu 19)
But apphost still runs on localhost:5000
I`ve also checked. I don’t have any variables like «urls».

If «ASPNETCORE_URLS» isn’t being trimmed to «URLS» then your config setup has been replaced. Are you building a config in Startup?
(Text, not screen shots please).
Hi @Tratcher ,
Yep, i have logic which builds IConfiguration from IConfigurationBuilder in my startup pipeline.
Thanks,
Stas
And then puts it into DI? That would explain the issue, you’re replacing the host config. One change from 2.x to 3.0 is that the host resolves IConfiguration from DI. The recommendation if you want to modify config is to do it in Program.CreateHostBuilder by calling ConfigureAppConfiguration. That appends to the default config rather than replacing it.
Yes, then i put it to DI.
serviceCollection.AddSingleton<IConfigurationBuilder>(serviceProvider => configBuilder);
serviceCollection.AddSingleton<IConfiguration>(serviceProvider => configBuilder.Build());
Thanks, i will check ConfigureAppConfiguration
Did ConfigureAppConfiguration resolve your issue?
Closing this as we haven’t heard from you and generally close issues with no response after some time. Please feel free to comment if you’re able to get the information we’re looking for and we can reopen the issue to investigate further!
I am not sure what is the final solution but
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>();
});
}
doesn’t pickup ASPNETCORE_URLS from environment.
my batch file looks like this
@ SET ASPNETCORE_ENVIRONMENT=development
@ SET DOTNET_PRINT_TELEMETRY_MESSAGE=false
@ SET ASPNETCORE_URLS=http://*:6003
@ SET ASPNETCORE_SERVER_URLS=http://*:6003
dotnet run
@AgrawalAshishS that sounds like a different issue. Can you file a new bug with a runnable sample that reproduces the problem? If it ends up being the same root cause, that’s fine, a new issue will help us ensure we triage this appropriately.
I got it resolved by updating my startup to take IConfiguration
public IConfiguration Configuration { get; }
private IWebHostEnvironment CurrentEnvironment { get; set; }
public Startup(IWebHostEnvironment env, IConfiguration configuration)
{
CurrentEnvironment = env;
Configuration = configuration;
}
@Tratcher the original author here was most likely trying to setup the environment variable on linux as a systemd process monitor to watch for dotnet behind apache or nginx (example)
@justlearntutors For environment variables, you need to escape the value http://localhost:5001 so systemd can parse it. Use the linux tool systemd-escape which gives http:--localhost:5001
groot@terminus:~$ systemd-escape http://localhost:5001
http:--localhost:5001
Note, this is different from the escaping the name on Linux to be compatible with .NET Core.
e.g. .NET Core setting appSettings:SuperSecretApiKey = Linux environment name appSettings__SuperSecretApiKey (two underscores __)
msftbot
bot
locked as resolved and limited conversation to collaborators
Jan 17, 2020
JunTaoLuo
added
the
area-runtime
Includes: Azure, Caching, Hosting, Middleware, Websockets, Kestrel, IIS, ANCM, HttpAbstractions
label
Jan 28, 2021
Labels
area-runtime
Includes: Azure, Caching, Hosting, Middleware, Websockets, Kestrel, IIS, ANCM, HttpAbstractions
feature-hosting
Includes: Hosting
March 15, 2021
After updating a .NET Core 2.2 app to NET 5, the following error appeared:
System.InvalidOperationException: ‘Application is running inside IIS process but is not configured to use IIS server.’
To fix this use HotBuilder instead of WebHostBuilder
public class Program
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder
.UseKestrel(serverOptions => serverOptions.AddServerHeader = false)
.UseIISIntegration()
.UseStartup<Startup>();
});
}
When you create a project .Net 5 with the Asp.Net Web Application template, it contains a Program.cs file. The contents of this file is presented below.
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>();
});
}
This class contains two methods: Main and CreateHostBuilder.
The Main method, like in most computer programs, is the entry point for our application. If we start our application in step-by-step mode (F10 or F11), our first stop will be on the opening accolade of this method.

The second CreateHostBuilder method returns an IHostBuilder object. Let’s define what a host is.
A Host is an object which implements IHost that will handle:
- The start of our application and its life cycle
- The injection of dependencies
- Logging
- Setting up our app
- …
This item will be generated by the Build() method of our IHostBuilder instance. We can see in the code that we retrieve this instance via the following line:
Host.CreateDefaultBuilder(args)
Host.cs
The Host class is a static class available in the Microsoft.Extensions.Hosting library, which contains two methods: CreateDefaultBuilder() and CreateDefaultBuilder (args).To fully understand the magic behind this method, let’s take advantage of the library’s source code available on GitHub and analyze the source code of this static class.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.EventLog;
namespace Microsoft.Extensions.Hosting
{
/// <summary>
/// Provides convenience methods for creating instances of <see cref="IHostBuilder"/> with pre-configured defaults.
/// </summary>
public static class Host
{
/// <summary>
/// Initializes a new instance of the <see cref="HostBuilder"/> class with pre-configured defaults.
/// </summary>
/// <remarks>
/// The following defaults are applied to the returned <see cref="HostBuilder"/>:
/// <list type="bullet">
/// <item><description>set the <see cref="IHostEnvironment.ContentRootPath"/> to the result of <see cref="Directory.GetCurrentDirectory()"/></description></item>
/// <item><description>load host <see cref="IConfiguration"/> from "DOTNET_" prefixed environment variables</description></item>
/// <item><description>load app <see cref="IConfiguration"/> from 'appsettings.json' and 'appsettings.[<see cref="IHostEnvironment.EnvironmentName"/>].json'</description></item>
/// <item><description>load app <see cref="IConfiguration"/> from User Secrets when <see cref="IHostEnvironment.EnvironmentName"/> is 'Development' using the entry assembly</description></item>
/// <item><description>load app <see cref="IConfiguration"/> from environment variables</description></item>
/// <item><description>configure the <see cref="ILoggerFactory"/> to log to the console, debug, and event source output</description></item>
/// <item><description>enables scope validation on the dependency injection container when <see cref="IHostEnvironment.EnvironmentName"/> is 'Development'</description></item>
/// </list>
/// </remarks>
/// <returns>The initialized <see cref="IHostBuilder"/>.</returns>
public static IHostBuilder CreateDefaultBuilder() =>
CreateDefaultBuilder(args: null);
/// <summary>
/// Initializes a new instance of the <see cref="HostBuilder"/> class with pre-configured defaults.
/// </summary>
/// <remarks>
/// The following defaults are applied to the returned <see cref="HostBuilder"/>:
/// <list type="bullet">
/// <item><description>set the <see cref="IHostEnvironment.ContentRootPath"/> to the result of <see cref="Directory.GetCurrentDirectory()"/></description></item>
/// <item><description>load host <see cref="IConfiguration"/> from "DOTNET_" prefixed environment variables</description></item>
/// <item><description>load host <see cref="IConfiguration"/> from supplied command line args</description></item>
/// <item><description>load app <see cref="IConfiguration"/> from 'appsettings.json' and 'appsettings.[<see cref="IHostEnvironment.EnvironmentName"/>].json'</description></item>
/// <item><description>load app <see cref="IConfiguration"/> from User Secrets when <see cref="IHostEnvironment.EnvironmentName"/> is 'Development' using the entry assembly</description></item>
/// <item><description>load app <see cref="IConfiguration"/> from environment variables</description></item>
/// <item><description>load app <see cref="IConfiguration"/> from supplied command line args</description></item>
/// <item><description>configure the <see cref="ILoggerFactory"/> to log to the console, debug, and event source output</description></item>
/// <item><description>enables scope validation on the dependency injection container when <see cref="IHostEnvironment.EnvironmentName"/> is 'Development'</description></item>
/// </list>
/// </remarks>
/// <param name="args">The command line args.</param>
/// <returns>The initialized <see cref="IHostBuilder"/>.</returns>
public static IHostBuilder CreateDefaultBuilder(string[] args)
{
var builder = new HostBuilder();
builder.UseContentRoot(Directory.GetCurrentDirectory());
builder.ConfigureHostConfiguration(config =>
{
config.AddEnvironmentVariables(prefix: "DOTNET_");
if (args != null)
{
config.AddCommandLine(args);
}
});
builder.ConfigureAppConfiguration((hostingContext, config) =>
{
IHostEnvironment env = hostingContext.HostingEnvironment;
bool reloadOnChange = hostingContext.Configuration.GetValue("hostBuilder:reloadConfigOnChange", defaultValue: true);
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: reloadOnChange)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: reloadOnChange);
if (env.IsDevelopment() && !string.IsNullOrEmpty(env.ApplicationName))
{
var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
if (appAssembly != null)
{
config.AddUserSecrets(appAssembly, optional: true);
}
}
config.AddEnvironmentVariables();
if (args != null)
{
config.AddCommandLine(args);
}
})
.ConfigureLogging((hostingContext, logging) =>
{
bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
// IMPORTANT: This needs to be added *before* configuration is loaded, this lets
// the defaults be overridden by the configuration.
if (isWindows)
{
// Default the EventLogLoggerProvider to warning or above
logging.AddFilter<EventLogLoggerProvider>(level => level >= LogLevel.Warning);
}
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
logging.AddEventSourceLogger();
if (isWindows)
{
// Add the EventLogLoggerProvider on windows machines
logging.AddEventLog();
}
logging.Configure(options =>
{
options.ActivityTrackingOptions = ActivityTrackingOptions.SpanId
| ActivityTrackingOptions.TraceId
| ActivityTrackingOptions.ParentId;
});
})
.UseDefaultServiceProvider((context, options) =>
{
bool isDevelopment = context.HostingEnvironment.IsDevelopment();
options.ValidateScopes = isDevelopment;
options.ValidateOnBuild = isDevelopment;
});
return builder;
}
}
}
The CreateDefaultBuilder() method simply calls the method CreateDefaultBuilder(string[] args) by passing it the null value.
var builder = new HostBuilder();
The CreateDefaultBuilder(string[] args) method begins with the instanciation of an object of type HostBuilder (who inherits IHostBuilder).We can directly call the Build().Run() method on this instance to start our Asp.Net host, but this one will have no configuration.
Host configuration
builder.UseContentRoot(Directory.GetCurrentDirectory());
This method defines the directory in which the Host will be executed. Our Host will therefore, by default, be executed in the directory from which the CLI dotnet command will be launched.
builder.ConfigureHostConfiguration(config =>
{
config.AddEnvironmentVariables(prefix: "DOTNET_");
if (args != null)
{
config.AddCommandLine(args);
}
});
This part concerns, as the name suggests, the host configuration.There may be some confusion about the ConfigureHostConfiguration method and the ConfigureAppConfiguration method since they receive a delegate with an IConfigurationBuilder parameter.What we can remember is that the configuration of a Host only concerns the following:
- The name of the app
- The environment
- The root repertoire
- The Kestrel
The UseContentRoot method simply add a configuration to our Host
All other configurations are about the app configuration. So the next step is to set up the app.
Setting up the app
builder.ConfigureAppConfiguration((hostingContext, config) =>
{
IHostEnvironment env = hostingContext.HostingEnvironment;
bool reloadOnChange = hostingContext.Configuration.GetValue("hostBuilder:reloadConfigOnChange", defaultValue: true);
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: reloadOnChange)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: reloadOnChange);
if (env.IsDevelopment() && !string.IsNullOrEmpty(env.ApplicationName))
{
var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
if (appAssembly != null)
{
config.AddUserSecrets(appAssembly, optional: true);
}
}
config.AddEnvironmentVariables();
if (args != null)
{
config.AddCommandLine(args);
}
});
The variable hostingContext.HostingEnvironment contains the environment in which our application will be run (Development, staging or production).
Loading configuration files
bool reloadOnChange = hostingContext.Configuration.GetValue("hostBuilder:reloadConfigOnChange", defaultValue: true);
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: reloadOnChange)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: reloadOnChange);
The configuration of the app starts by loading our two appsettings.json files.This action is done using the AddJsonFile method. This method takes 3 parameters:
- Path (string): The path to json files. The path is relative, and is based on the directory we pass in parameter to the Method UseContentRoot().
- Optional (bool): Specifies whether the file is required (false) or is optional (true). If the setting has the false value and the file is not found, a FileNotFoundException exception is generated and our app will not launch.
- ReloadOnChange (bool): If the value is true, the values will be self-reloaded while our app runs if the content of the file changes.
bool reloadOnChange = hostingContext.Configuration.GetValue("hostBuilder:reloadConfigOnChange", defaultValue: true);
This line is new in .Net 5. In.Net Core 3.x, the value of reloadOnChange was consistently true. Here it is possible to put the value to false by adding the following configuration “hostBuilder:reloadConfigOnChange” to false.
Added User Secrets
if (env.IsDevelopment() && !string.IsNullOrEmpty(env.ApplicationName))
{
var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
if (appAssembly != null)
{
config.AddUserSecrets(appAssembly, optional: true);
}
}
App settings containing sensitive data should not be stored in a repository. In.Net Core, the User Secrets mechanism allows us to have a secret.json file that will replace the data present in the appSettings.json file. If you’ve saved Secret Users in your environment, this part will load them.
Logging
.ConfigureLogging((hostingContext, logging) =>
{
bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
// IMPORTANT: This needs to be added *before* configuration is loaded, this lets
// the defaults be overridden by the configuration.
if (isWindows)
{
// Default the EventLogLoggerProvider to warning or above
logging.AddFilter<EventLogLoggerProvider>(level => level >= LogLevel.Warning);
}
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
logging.AddEventSourceLogger();
if (isWindows)
{
// Add the EventLogLoggerProvider on windows machines
logging.AddEventLog();
}
logging.Configure(options =>
{
options.ActivityTrackingOptions = ActivityTrackingOptions.SpanId
| ActivityTrackingOptions.TraceId
| ActivityTrackingOptions.ParentId;
});
})
This step involves setting up logs generated by the application. We can see that if the app runs on Windows, logs with a higher level than warning will be written in the Windows EventLog, but will also be written in the console (AddConsole) and also in the Output window in Visual Studio (AddDebug).AddEventSourceLogger adds The Tracing Event.
Dependency injection
.UseDefaultServiceProvider((context, options) =>
{
bool isDevelopment = context.HostingEnvironment.IsDevelopment();
options.ValidateScopes = isDevelopment;
options.ValidateOnBuild = isDevelopment;
});
The final step in our CreateDefaultBuilder method is to add the dependency injection to our app. The UseDefaultServiceProvider method allows the native IOC container of .Net Core to be added. If the ValidateScopes option is true, it will raise an exception if you try to resolve a dependency registered as Scoped in a method that has no scope (for example, if you try to resolve your dependency in the Configure method of your class Startup.cs).
The ValidateOnBuild method is a new feature of the .Net Core 3 which, if its value is true, will launch an exception if one of your class needs an dependency that we would have forgotten to register. I invite you to read my articles to learn more about dependency injection.
Conclusion
The Host method.CreateDefaultBuilder (args) now has no secrets for you. In a future article, I’ll show you how to create an app in .Net Core without using this method. See you soon 🙂
Я следую этому руководству https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/working-with-sql?view=aspnetcore-3.0&tabs=visual -studio я получаю следующее сообщение об ошибке: Хост имени не существует в текущем контексте
Вот как выглядит мой файл Program.cs
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using MvcMovie.Data;
using MvcMovie.Models;
using System;
namespace MvcMovie
{
public class Program
{
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
SeedData.Initialize(services);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred seeding the DB.");
}
}
host.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
Красная линия под Host.CreateDefaultBuilder (args)
1 ответ
Лучший ответ
В указанном вами руководстве используется версия 3.0, но содержимое вашего .csproj показывает, что вы используете 2.1. Host.CreateDefaultBuilder недоступен в 2.1, поэтому у вас есть два варианта:
- Переключитесь на версию учебника 2.1, в которой используется
WebHost.CreateDefaultBuilder. Это можно сделать с помощью селектора «Версия» на страницах документации ASP.NET Core. - Используйте версию учебника 3.0 (или 3.1) и соответствующим образом настройте свой проект. Для этого вам просто нужна соответствующая версия SDK и Visual Studio.
Если вы можете , используйте версию 3.1. Это рекомендуемая версия LTS.
4
Kirk Larkin
17 Дек 2019 в 02:42
I created an ASP.NET Core 3.0 Web Application with the default template in Visual Studio 2019 Preview 2.2 and tried to inject an ILogger in Startup:
namespace WebApplication1
{
public class Startup
{
private readonly ILogger _logger;
public Startup(IConfiguration configuration, ILogger<Startup> logger)
{
Configuration = configuration;
_logger = logger;
}
// ...
}
}
In Program.cs I also call the ConfigureLogging() method:
namespace WebApplication1
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.ClearProviders();
logging.AddConsole();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
It works in ASP.NET Core 2.x but in ASP.NET Core 3 it fails with the following error:
System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger`1[WebApplication1.Startup]' while attempting to activate 'WebApplication1.Startup'.
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
at Microsoft.AspNetCore.Hosting.Internal.GenericWebHostBuilder.UseStartup(Type startupType, HostBuilderContext context, IServiceCollection services)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Hosting.Internal.GenericWebHostBuilder.<>c__DisplayClass13_0.<UseStartup>b__2(IApplicationBuilder app)
at Microsoft.AspNetCore.Server.IIS.Core.IISServerSetupFilter.<>c__DisplayClass2_0.<Configure>b__0(IApplicationBuilder app)
at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
at Microsoft.AspNetCore.Hosting.Internal.GenericWebHostService.StartAsync(CancellationToken cancellationToken)
Any idea on what is causing this behavior?
Below the full Program.cs and Startup.cs files from the default «Web Application» template, only logging was added.
Program.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace WebApplication1
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.ClearProviders();
logging.AddConsole();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace WebApplication1
{
public class Startup
{
private readonly ILogger _logger;
public Startup(IConfiguration configuration, ILogger<Startup> logger)
{
Configuration = configuration;
_logger = logger;
}
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.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
//services.AddTransient(typeof(ILogger<>), (typeof(Logger<>)));
services.AddMvc()
.AddNewtonsoftJson();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting(routes =>
{
routes.MapApplication();
});
app.UseCookiePolicy();
app.UseAuthorization();
}
}
}