Запуск приложения в ASP.NET CoreApp startup in ASP.NET Core
Авторы: Рик Андерсон (Rick Anderson), Том Дайкстра (Tom Dykstra) и Стив Смит (Steve Smith)By Rick Anderson, Tom Dykstra, and Steve Smith
Класс Startup
настраивает службы и конвейер запросов приложения.The Startup
class configures services and the app's request pipeline.
Класс StartupThe Startup class
Приложения ASP.NET Core используют класс Startup
, который по соглашению называется Startup
.ASP.NET Core apps use a Startup
class, which is named Startup
by convention. Класс Startup
:The Startup
class:
- При необходимости содержит метод ConfigureServices для настройки служб приложения.Optionally includes a ConfigureServices method to configure the app's services. Служба — многократно используемый компонент, обеспечивающий функциональность приложения.A service is a reusable component that provides app functionality. Службы регистрируются в
ConfigureServices
и используются в приложении с помощью внедрения зависимостей (DI) или ApplicationServices.Services are registered inConfigureServices
and consumed across the app via dependency injection (DI) or ApplicationServices. - Содержит метод Configure для создания конвейера обработки запросов приложения.Includes a Configure method to create the app's request processing pipeline.
ConfigureServices
и Configure
вызываются средой выполнения ASP.NET Core при запуске приложения:ConfigureServices
and Configure
are called by the ASP.NET Core runtime when the app starts:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
Предыдущий пример предназначен для Razor Pages; версия для MVC похожа.The preceding sample is for Razor Pages; the MVC version is similar.
Класс Startup
указывается при создании узла приложения.The Startup
class is specified when the app's host is built. Класс Startup
обычно указывается путем вызова метода WebHostBuilderExtensions.UseStartup<TStartup> в построителе узлов.The Startup
class is typically specified by calling the WebHostBuilderExtensions.UseStartup<TStartup> method on the host builder:
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>();
});
}
Узел предоставляет службы, которые доступны конструктору классов Startup
.The host provides services that are available to the Startup
class constructor. Приложение добавляет дополнительные службы через ConfigureServices
.The app adds additional services via ConfigureServices
. Как службы узла, так и службы приложения доступны в Configure
и во всем приложении.Both the host and app services are available in Configure
and throughout the app.
При использовании универсального узла (IHostBuilder) в конструктор Startup
могут внедряться только следующие типы служб:Only the following service types can be injected into the Startup
constructor when using the Generic Host (IHostBuilder):
public class Startup
{
private readonly IWebHostEnvironment _env;
public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
Configuration = configuration;
_env = env;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
if (_env.IsDevelopment())
{
}
else
{
}
}
}
Большинство служб недоступны, пока не будет вызван метод Configure
.Most services are not available until the Configure
method is called.
Несколько запусковMultiple Startup
Когда приложение определяет отдельные классы Startup
для различных сред (например, StartupDevelopment
), подходящий класс Startup
выбирается во время выполнения.When the app defines separate Startup
classes for different environments (for example, StartupDevelopment
), the appropriate Startup
class is selected at runtime. Класс, у которого суффикс имени соответствует текущей среде, получает приоритет.The class whose name suffix matches the current environment is prioritized. Если приложение выполняется в среде разработки и включает в себя оба класса — Startup
и StartupDevelopment
, используется класс StartupDevelopment
.If the app is run in the Development environment and includes both a Startup
class and a StartupDevelopment
class, the StartupDevelopment
class is used. Дополнительные сведения см. в статье Использование нескольких сред.For more information, see Use multiple environments.
Дополнительные сведения об узле см. в разделе Узел.See The host for more information on the host. Сведения об обработке ошибок во время запуска см. в разделе Обработка исключений при запуске.For information on handling errors during startup, see Startup exception handling.
Метод ConfigureServicesThe ConfigureServices method
Метод ConfigureServices:The ConfigureServices method is:
- Необязательный элемент.Optional.
- Вызывается узлом перед методом
Configure
для настройки служб приложения.Called by the host before theConfigure
method to configure the app's services. - По соглашению используется для задания параметров конфигурации.Where configuration options are set by convention.
Узел может настраивать некоторые службы перед вызовом методов Startup
.The host may configure some services before Startup
methods are called. Дополнительную информацию см. в разделе Узел.For more information, see The host.
Для функций, нуждающихся в значительной настройке, существуют методы расширения Add{Service}
в IServiceCollection.For features that require substantial setup, there are Add{Service}
extension methods on IServiceCollection. Например, Add DbContext, Add DefaultIdentity, Add EntityFrameworkStores и AddRazorPages:For example, Add DbContext, Add DefaultIdentity, Add EntityFrameworkStores, and AddRazorPages:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
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.AddRazorPages();
}
Добавление служб в контейнер служб делает их доступными в приложении и в методе Configure
.Adding services to the service container makes them available within the app and in the Configure
method. Службы разрешаются посредством внедрения зависимостей или из ApplicationServices.The services are resolved via dependency injection or from ApplicationServices.
Метод ConfigureThe Configure method
Метод Configure используется для указания того, как приложение реагирует на HTTP-запросы.The Configure method is used to specify how the app responds to HTTP requests. Конвейер запросов настраивается путем добавления компонентов ПО промежуточного слоя в экземпляр IApplicationBuilder.The request pipeline is configured by adding middleware components to an IApplicationBuilder instance. IApplicationBuilder
доступен для метода Configure
, но он не зарегистрирован в контейнере службы.IApplicationBuilder
is available to the Configure
method, but it isn't registered in the service container. При размещении создается IApplicationBuilder
и передается непосредственно в Configure
.Hosting creates an IApplicationBuilder
and passes it directly to Configure
.
Шаблоны ASP.NET Core настраивают конвейер с поддержкой следующих компонентов и функций:The ASP.NET Core templates configure the pipeline with support for:
- Страница со сведениями об исключении для разработчикаDeveloper Exception Page
- обработчиков исключений;Exception handler
- HTTP Strict Transport Security (HSTS)HTTP Strict Transport Security (HSTS)
- перенаправления HTTPS;HTTPS redirection
- Статические файлыStatic files
- ASP.NET Core MVC и Razor PagesASP.NET Core MVC and Razor Pages
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});
}
}
Предыдущий пример предназначен для Razor Pages; версия для MVC похожа.The preceding sample is for Razor Pages; the MVC version is similar.
Каждый метод расширения Use
добавляет один или несколько компонентов ПО промежуточного слоя в конвейер запросов.Each Use
extension method adds one or more middleware components to the request pipeline. Например, UseStaticFiles настраивает ПО промежуточного слоя для обслуживания статических файлов.For instance, UseStaticFiles configures middleware to serve static files.
Каждый компонент ПО промежуточного слоя в конвейере запросов отвечает за вызов следующего компонента в конвейере или замыкает цепочку, если это необходимо.Each middleware component in the request pipeline is responsible for invoking the next component in the pipeline or short-circuiting the chain, if appropriate.
В сигнатуре метода Configure
могут быть указаны дополнительные службы, такие как IWebHostEnvironment
, ILoggerFactory
или любые службы, определенные в ConfigureServices
.Additional services, such as IWebHostEnvironment
, ILoggerFactory
, or anything defined in ConfigureServices
, can be specified in the Configure
method signature. Эти службы внедряются, если доступны.These services are injected if they're available.
Дополнительные сведения об использовании IApplicationBuilder
и порядке обработки ПО промежуточного слоя см. в статье ПО промежуточного слоя ASP.NET Core.For more information on how to use IApplicationBuilder
and the order of middleware processing, see ПО промежуточного слоя ASP.NET Core.
Настройка служб без запускаConfigure services without Startup
Для настройки служб и конвейера обработки запросов в построителе узлов вместо класса Startup
можно использовать удобные методы ConfigureServices
и Configure
.To configure services and the request processing pipeline without using a Startup
class, call ConfigureServices
and Configure
convenience methods on the host builder. Несколько вызовов ConfigureServices
добавляются друг к другу.Multiple calls to ConfigureServices
append to one another. При наличии нескольких вызовов метода Configure
используется последний вызов Configure
.If multiple Configure
method calls exist, the last Configure
call is used.
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureServices(services =>
{
services.AddControllersWithViews();
})
.Configure(app =>
{
var loggerFactory = app.ApplicationServices
.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger<Program>();
var env = app.ApplicationServices.GetRequiredService<IWebHostEnvironment>();
var config = app.ApplicationServices.GetRequiredService<IConfiguration>();
logger.LogInformation("Logged in Configure");
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
var configValue = config["MyConfigKey"];
});
});
});
}
Расширение класса Startup с использованием фильтров запускаExtend Startup with startup filters
Используйте IStartupFilter в следующих случаях:Use IStartupFilter:
- Для настройки ПО промежуточного слоя в начале или конце конвейера ПО промежуточного слоя Configure приложения без явного вызова
Use{Middleware}
.To configure middleware at the beginning or end of an app's Configure middleware pipeline without an explicit call toUse{Middleware}
. ASP.NET Core используетIStartupFilter
для добавления значений по умолчанию в начало конвейера, исключая необходимость явной регистрации ПО промежуточного слоя по умолчанию автором приложения.IStartupFilter
is used by ASP.NET Core to add defaults to the beginning of the pipeline without having to make the app author explicitly register the default middleware.IStartupFilter
разрешает другим компонентам вызыватьUse{Middleware}
от имени автора приложения.IStartupFilter
allows a different component to callUse{Middleware}
on behalf of the app author. - Для создания конвейера методов
Configure
.To create a pipeline ofConfigure
methods. IStartupFilter.Configure может обеспечивать запуск ПО промежуточного слоя до или после ПО промежуточного слоя, добавляемого библиотеками.IStartupFilter.Configure can set a middleware to run before or after middleware added by libraries.
IStartupFilter
реализует метод Configure, который принимает и возвращает Action<IApplicationBuilder>
.IStartupFilter
implements Configure, which receives and returns an Action<IApplicationBuilder>
. IApplicationBuilder определяет класс для настройки конвейера запросов приложения.An IApplicationBuilder defines a class to configure an app's request pipeline. Дополнительные сведения см. в разделе Создание конвейера ПО промежуточного слоя с помощью IApplicationBuilder.For more information, see Create a middleware pipeline with IApplicationBuilder.
Каждый интерфейс IStartupFilter
может добавлять один или несколько компонентов ПО промежуточного слоя в конвейер запросов.Each IStartupFilter
can add one or more middlewares in the request pipeline. Фильтры вызываются в том порядке, в котором они были добавлены в контейнер службы.The filters are invoked in the order they were added to the service container. Фильтры могут добавлять ПО промежуточного слоя до или после передачи управления следующему фильтру, поэтому они добавляются в начало или конец конвейера приложения.Filters may add middleware before or after passing control to the next filter, thus they append to the beginning or end of the app pipeline.
В следующем примере показана регистрация ПО промежуточного слоя с помощью IStartupFilter
.The following example demonstrates how to register a middleware with IStartupFilter
. ПО промежуточного слоя RequestSetOptionsMiddleware
задает значения параметров из параметра строки запроса:The RequestSetOptionsMiddleware
middleware sets an options value from a query string parameter:
public class RequestSetOptionsMiddleware
{
private readonly RequestDelegate _next;
public RequestSetOptionsMiddleware( RequestDelegate next )
{
_next = next;
}
// Test with https://localhost:5001/Privacy/?option=Hello
public async Task Invoke(HttpContext httpContext)
{
var option = httpContext.Request.Query["option"];
if (!string.IsNullOrWhiteSpace(option))
{
httpContext.Items["option"] = WebUtility.HtmlEncode(option);
}
await _next(httpContext);
}
}
RequestSetOptionsMiddleware
настраивается в классе RequestSetOptionsStartupFilter
:The RequestSetOptionsMiddleware
is configured in the RequestSetOptionsStartupFilter
class:
public class RequestSetOptionsStartupFilter : IStartupFilter
{
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
{
return builder =>
{
builder.UseMiddleware<RequestSetOptionsMiddleware>();
next(builder);
};
}
}
IStartupFilter
регистрируется в контейнере службы в ConfigureServices.The IStartupFilter
is registered in the service container in ConfigureServices.
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureServices(services =>
{
services.AddTransient<IStartupFilter,
RequestSetOptionsStartupFilter>();
});
}
Если указан параметр строки запроса для option
, ПО промежуточного слоя обрабатывает присвоение значения до того, как ПО промежуточного слоя ASP.NET Core отображает ответ.When a query string parameter for option
is provided, the middleware processes the value assignment before the ASP.NET Core middleware renders the response.
Порядок выполнения ПО промежуточного слоя определяется порядком регистраций IStartupFilter
:Middleware execution order is set by the order of IStartupFilter
registrations:
Несколько реализаций
IStartupFilter
могут взаимодействовать с одними и теми же объектами.MultipleIStartupFilter
implementations may interact with the same objects. Если важен порядок, упорядочите регистрации службыIStartupFilter
в соответствии с требуемым порядком выполнения ПО промежуточного слоя.If ordering is important, order theirIStartupFilter
service registrations to match the order that their middlewares should run.Библиотеки могут добавлять ПО промежуточного слоя с одной или несколькими реализациями
IStartupFilter
, которые выполняются до или после другого ПО промежуточного слоя приложения, зарегистрированного с помощьюIStartupFilter
.Libraries may add middleware with one or moreIStartupFilter
implementations that run before or after other app middleware registered withIStartupFilter
. Чтобы вызвать ПО промежуточного слояIStartupFilter
до ПО промежуточного слоя, добавляемого библиотекойIStartupFilter
, сделайте следующее:To invoke anIStartupFilter
middleware before a middleware added by a library'sIStartupFilter
:- расположите регистрацию службы до добавления библиотеки в контейнер службы.Position the service registration before the library is added to the service container.
- Чтобы вызвать его после этого момента, расположите регистрацию службы после добавления библиотеки.To invoke afterward, position the service registration after the library is added.
Добавление конфигурации из внешней сборки при запускеAdd configuration at startup from an external assembly
Реализация IHostingStartup позволяет при запуске добавлять в приложение улучшения из внешней сборки вне приложения класса Startup
.An IHostingStartup implementation allows adding enhancements to an app at startup from an external assembly outside of the app's Startup
class. Для получения дополнительной информации см. Использование начальных сборок размещения в ASP.NET Core.For more information, see Использование начальных сборок размещения в ASP.NET Core.
Дополнительные ресурсыAdditional resources
Класс StartupThe Startup class
Приложения ASP.NET Core используют класс Startup
, который по соглашению называется Startup
.ASP.NET Core apps use a Startup
class, which is named Startup
by convention. Класс Startup
:The Startup
class:
- При необходимости содержит метод ConfigureServices для настройки служб приложения.Optionally includes a ConfigureServices method to configure the app's services. Служба — многократно используемый компонент, обеспечивающий функциональность приложения.A service is a reusable component that provides app functionality. Службы регистрируются в
ConfigureServices
и используются в приложении с помощью внедрения зависимостей (DI) или ApplicationServices.Services are registered inConfigureServices
and consumed across the app via dependency injection (DI) or ApplicationServices. - Содержит метод Configure для создания конвейера обработки запросов приложения.Includes a Configure method to create the app's request processing pipeline.
ConfigureServices
и Configure
вызываются средой выполнения ASP.NET Core при запуске приложения:ConfigureServices
and Configure
are called by the ASP.NET Core runtime when the app starts:
public class Startup
{
// Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
...
}
// Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
...
}
}
Класс Startup
указывается при создании узла приложения.The Startup
class is specified when the app's host is built. Класс Startup
обычно указывается путем вызова метода WebHostBuilderExtensions.UseStartup<TStartup> в построителе узлов.The Startup
class is typically specified by calling the WebHostBuilderExtensions.UseStartup<TStartup> method on the host builder:
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
Узел предоставляет службы, которые доступны конструктору классов Startup
.The host provides services that are available to the Startup
class constructor. Приложение добавляет дополнительные службы через ConfigureServices
.The app adds additional services via ConfigureServices
. Как службы узла, так и службы приложения доступны в Configure
и во всем приложении.Both the host and app services are then available in Configure
and throughout the app.
Типичным применением внедрения зависимостей в класс Startup
является внедрение:A common use of dependency injection into the Startup
class is to inject:
- IHostingEnvironment для настройки служб средой;IHostingEnvironment to configure services by environment.
- IConfiguration для чтения конфигурации;IConfiguration to read configuration.
- ILoggerFactory для создания средства ведения журнала в
Startup.ConfigureServices
.ILoggerFactory to create a logger inStartup.ConfigureServices
.
public class Startup
{
private readonly IHostingEnvironment _env;
private readonly IConfiguration _config;
private readonly ILoggerFactory _loggerFactory;
public Startup(IHostingEnvironment env, IConfiguration config,
ILoggerFactory loggerFactory)
{
_env = env;
_config = config;
_loggerFactory = loggerFactory;
}
public void ConfigureServices(IServiceCollection services)
{
var logger = _loggerFactory.CreateLogger<Startup>();
if (_env.IsDevelopment())
{
// Development service configuration
logger.LogInformation("Development environment");
}
else
{
// Non-development service configuration
logger.LogInformation("Environment: {EnvironmentName}", _env.EnvironmentName);
}
// Configuration is available during startup.
// Examples:
// _config["key"]
// _config["subsection:suboption1"]
}
}
Большинство служб недоступны, пока не будет вызван метод Configure
.Most services are not available until the Configure
method is called.
Несколько запусковMultiple Startup
Когда приложение определяет отдельные классы Startup
для различных сред (например, StartupDevelopment
), подходящий класс Startup
выбирается во время выполнения.When the app defines separate Startup
classes for different environments (for example, StartupDevelopment
), the appropriate Startup
class is selected at runtime. Класс, у которого суффикс имени соответствует текущей среде, получает приоритет.The class whose name suffix matches the current environment is prioritized. Если приложение выполняется в среде разработки и включает в себя оба класса — Startup
и StartupDevelopment
, используется класс StartupDevelopment
.If the app is run in the Development environment and includes both a Startup
class and a StartupDevelopment
class, the StartupDevelopment
class is used. Дополнительные сведения см. в статье Использование нескольких сред.For more information, see Use multiple environments.
Дополнительные сведения об узле см. в разделе Узел.See The host for more information on the host. Сведения об обработке ошибок во время запуска см. в разделе Обработка исключений при запуске.For information on handling errors during startup, see Startup exception handling.
Метод ConfigureServicesThe ConfigureServices method
Метод ConfigureServices:The ConfigureServices method is:
- Необязательный элемент.Optional.
- Вызывается узлом перед методом
Configure
для настройки служб приложения.Called by the host before theConfigure
method to configure the app's services. - По соглашению используется для задания параметров конфигурации.Where configuration options are set by convention.
Узел может настраивать некоторые службы перед вызовом методов Startup
.The host may configure some services before Startup
methods are called. Дополнительную информацию см. в разделе Узел.For more information, see The host.
Для функций, нуждающихся в значительной настройке, существуют методы расширения Add{Service}
в IServiceCollection.For features that require substantial setup, there are Add{Service}
extension methods on IServiceCollection. Например, Add DbContext, Add DefaultIdentity, Add EntityFrameworkStores и AddRazorPages:For example, Add DbContext, Add DefaultIdentity, Add EntityFrameworkStores, and AddRazorPages:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>()
.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
Добавление служб в контейнер служб делает их доступными в приложении и в методе Configure
.Adding services to the service container makes them available within the app and in the Configure
method. Службы разрешаются посредством внедрения зависимостей или из ApplicationServices.The services are resolved via dependency injection or from ApplicationServices.
Подробнее о SetCompatibilityVersion
см. в сведениях о SetCompatibilityVersion.See SetCompatibilityVersion for more information on SetCompatibilityVersion
.
Метод ConfigureThe Configure method
Метод Configure используется для указания того, как приложение реагирует на HTTP-запросы.The Configure method is used to specify how the app responds to HTTP requests. Конвейер запросов настраивается путем добавления компонентов ПО промежуточного слоя в экземпляр IApplicationBuilder.The request pipeline is configured by adding middleware components to an IApplicationBuilder instance. IApplicationBuilder
доступен для метода Configure
, но он не зарегистрирован в контейнере службы.IApplicationBuilder
is available to the Configure
method, but it isn't registered in the service container. При размещении создается IApplicationBuilder
и передается непосредственно в Configure
.Hosting creates an IApplicationBuilder
and passes it directly to Configure
.
Шаблоны ASP.NET Core настраивают конвейер с поддержкой следующих компонентов и функций:The ASP.NET Core templates configure the pipeline with support for:
- Страница со сведениями об исключении для разработчикаDeveloper Exception Page
- обработчиков исключений;Exception handler
- HTTP Strict Transport Security (HSTS)HTTP Strict Transport Security (HSTS)
- перенаправления HTTPS;HTTPS redirection
- Статические файлыStatic files
- ASP.NET Core MVC и Razor PagesASP.NET Core MVC and Razor Pages
- общего регламента по защите данных (GDPR);General Data Protection Regulation (GDPR)
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc();
}
Каждый метод расширения Use
добавляет один или несколько компонентов ПО промежуточного слоя в конвейер запросов.Each Use
extension method adds one or more middleware components to the request pipeline. Например, UseStaticFiles настраивает ПО промежуточного слоя для обслуживания статических файлов.For instance, UseStaticFiles configures middleware to serve static files.
Каждый компонент ПО промежуточного слоя в конвейере запросов отвечает за вызов следующего компонента в конвейере или замыкает цепочку, если это необходимо.Each middleware component in the request pipeline is responsible for invoking the next component in the pipeline or short-circuiting the chain, if appropriate.
В сигнатуре метода Configure
могут быть указаны дополнительные службы, такие как IHostingEnvironment
, ILoggerFactory
или любые службы, определенные в ConfigureServices
.Additional services, such as IHostingEnvironment
and ILoggerFactory
, or anything defined in ConfigureServices
, can be specified in the Configure
method signature. Эти службы внедряются, если доступны.These services are injected if they're available.
Дополнительные сведения об использовании IApplicationBuilder
и порядке обработки ПО промежуточного слоя см. в статье ПО промежуточного слоя ASP.NET Core.For more information on how to use IApplicationBuilder
and the order of middleware processing, see ПО промежуточного слоя ASP.NET Core.
Настройка служб без запускаConfigure services without Startup
Для настройки служб и конвейера обработки запросов в построителе узлов вместо класса Startup
можно использовать удобные методы ConfigureServices
и Configure
.To configure services and the request processing pipeline without using a Startup
class, call ConfigureServices
and Configure
convenience methods on the host builder. Несколько вызовов ConfigureServices
добавляются друг к другу.Multiple calls to ConfigureServices
append to one another. При наличии нескольких вызовов метода Configure
используется последний вызов Configure
.If multiple Configure
method calls exist, the last Configure
call is used.
public class Program
{
public static IHostingEnvironment HostingEnvironment { get; set; }
public static IConfiguration Configuration { get; set; }
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
})
.ConfigureServices(services =>
{
...
})
.Configure(app =>
{
var loggerFactory = app.ApplicationServices
.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger<Program>();
var env = app.ApplicationServices.GetRequiredService<IHostingEnvironment>();
var config = app.ApplicationServices.GetRequiredService<IConfiguration>();
logger.LogInformation("Logged in Configure");
if (env.IsDevelopment())
{
...
}
else
{
...
}
var configValue = config["subsection:suboption1"];
...
});
}
Расширение класса Startup с использованием фильтров запускаExtend Startup with startup filters
Используйте IStartupFilter в следующих случаях:Use IStartupFilter:
- Для настройки ПО промежуточного слоя в начале или конце конвейера ПО промежуточного слоя Configure приложения без явного вызова
Use{Middleware}
.To configure middleware at the beginning or end of an app's Configure middleware pipeline without an explicit call toUse{Middleware}
. ASP.NET Core используетIStartupFilter
для добавления значений по умолчанию в начало конвейера, исключая необходимость явной регистрации ПО промежуточного слоя по умолчанию автором приложения.IStartupFilter
is used by ASP.NET Core to add defaults to the beginning of the pipeline without having to make the app author explicitly register the default middleware.IStartupFilter
разрешает другим компонентам вызыватьUse{Middleware}
от имени автора приложения.IStartupFilter
allows a different component callUse{Middleware}
on behalf of the app author. - Для создания конвейера методов
Configure
.To create a pipeline ofConfigure
methods. IStartupFilter.Configure может обеспечивать запуск ПО промежуточного слоя до или после ПО промежуточного слоя, добавляемого библиотеками.IStartupFilter.Configure can set a middleware to run before or after middleware added by libraries.
IStartupFilter
реализует метод Configure, который принимает и возвращает Action<IApplicationBuilder>
.IStartupFilter
implements Configure, which receives and returns an Action<IApplicationBuilder>
. IApplicationBuilder определяет класс для настройки конвейера запросов приложения.An IApplicationBuilder defines a class to configure an app's request pipeline. Дополнительные сведения см. в разделе Создание конвейера ПО промежуточного слоя с помощью IApplicationBuilder.For more information, see Create a middleware pipeline with IApplicationBuilder.
Каждый интерфейс IStartupFilter
может добавлять один или несколько компонентов ПО промежуточного слоя в конвейер запросов.Each IStartupFilter
can add one or more middlewares in the request pipeline. Фильтры вызываются в том порядке, в котором они были добавлены в контейнер службы.The filters are invoked in the order they were added to the service container. Фильтры могут добавлять ПО промежуточного слоя до или после передачи управления следующему фильтру, поэтому они добавляются в начало или конец конвейера приложения.Filters may add middleware before or after passing control to the next filter, thus they append to the beginning or end of the app pipeline.
В следующем примере показана регистрация ПО промежуточного слоя с помощью IStartupFilter
.The following example demonstrates how to register a middleware with IStartupFilter
. ПО промежуточного слоя RequestSetOptionsMiddleware
задает значения параметров из параметра строки запроса:The RequestSetOptionsMiddleware
middleware sets an options value from a query string parameter:
public class RequestSetOptionsMiddleware
{
private readonly RequestDelegate _next;
private IOptions<AppOptions> _injectedOptions;
public RequestSetOptionsMiddleware(
RequestDelegate next, IOptions<AppOptions> injectedOptions)
{
_next = next;
_injectedOptions = injectedOptions;
}
public async Task Invoke(HttpContext httpContext)
{
Console.WriteLine("RequestSetOptionsMiddleware.Invoke");
var option = httpContext.Request.Query["option"];
if (!string.IsNullOrWhiteSpace(option))
{
_injectedOptions.Value.Option = WebUtility.HtmlEncode(option);
}
await _next(httpContext);
}
}
RequestSetOptionsMiddleware
настраивается в классе RequestSetOptionsStartupFilter
:The RequestSetOptionsMiddleware
is configured in the RequestSetOptionsStartupFilter
class:
public class RequestSetOptionsStartupFilter : IStartupFilter
{
public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
{
return builder =>
{
builder.UseMiddleware<RequestSetOptionsMiddleware>();
next(builder);
};
}
}
IStartupFilter
регистрируется в контейнере службы в ConfigureServices.The IStartupFilter
is registered in the service container in ConfigureServices.
WebHost.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
services.AddTransient<IStartupFilter,
RequestSetOptionsStartupFilter>();
})
.UseStartup<Startup>()
.Build();
Если указан параметр строки запроса для option
, ПО промежуточного слоя обрабатывает присвоение значения до того, как ПО промежуточного слоя ASP.NET Core отображает ответ.When a query string parameter for option
is provided, the middleware processes the value assignment before the ASP.NET Core middleware renders the response.
Порядок выполнения ПО промежуточного слоя определяется порядком регистраций IStartupFilter
:Middleware execution order is set by the order of IStartupFilter
registrations:
Несколько реализаций
IStartupFilter
могут взаимодействовать с одними и теми же объектами.MultipleIStartupFilter
implementations may interact with the same objects. Если важен порядок, упорядочите регистрации службыIStartupFilter
в соответствии с требуемым порядком выполнения ПО промежуточного слоя.If ordering is important, order theirIStartupFilter
service registrations to match the order that their middlewares should run.Библиотеки могут добавлять ПО промежуточного слоя с одной или несколькими реализациями
IStartupFilter
, которые выполняются до или после другого ПО промежуточного слоя приложения, зарегистрированного с помощьюIStartupFilter
.Libraries may add middleware with one or moreIStartupFilter
implementations that run before or after other app middleware registered withIStartupFilter
. Чтобы вызвать ПО промежуточного слояIStartupFilter
до ПО промежуточного слоя, добавляемого библиотекойIStartupFilter
, сделайте следующее:To invoke anIStartupFilter
middleware before a middleware added by a library'sIStartupFilter
:- расположите регистрацию службы до добавления библиотеки в контейнер службы.Position the service registration before the library is added to the service container.
- Чтобы вызвать его после этого момента, расположите регистрацию службы после добавления библиотеки.To invoke afterward, position the service registration after the library is added.
Добавление конфигурации из внешней сборки при запускеAdd configuration at startup from an external assembly
Реализация IHostingStartup позволяет при запуске добавлять в приложение улучшения из внешней сборки вне приложения класса Startup
.An IHostingStartup implementation allows adding enhancements to an app at startup from an external assembly outside of the app's Startup
class. Для получения дополнительной информации см. Использование начальных сборок размещения в ASP.NET Core.For more information, see Использование начальных сборок размещения в ASP.NET Core.