Asp net windows linux

Содержание
  1. Установка пакета SDK для .NET или среды выполнения .NET вручную Install the .NET SDK or the .NET Runtime manually
  2. Выпуски .NET .NET releases
  3. Зависимости Dependencies
  4. Зависимости RPM RPM dependencies
  5. Зависимости DEB DEB dependencies
  6. Общие зависимости Common dependencies
  7. Установка с помощью скрипта Scripted install
  8. Установка вручную Manual install
  9. Download .NET
  10. .NET 5.0 (recommended)
  11. .NET Core 3.1
  12. .NET Framework 4.8
  13. .NET 5.0 (recommended)
  14. .NET Core 3.1
  15. .NET 5.0 (recommended)
  16. .NET Core 3.1
  17. .NET Core
  18. .NET Framework
  19. Free. Cross-platform. Open source. Supported.
  20. Thank You to All the Contributors
  21. Ready to Get Started?
  22. Размещение ASP.NET Core в операционной системе Linux с Apache Host ASP.NET Core on Linux with Apache
  23. Предварительные требования Prerequisites
  24. Публикация и копирование приложения Publish and copy over the app
  25. Настройка прокси-сервера Configure a proxy server
  26. Установка Apache Install Apache
  27. Настройка Apache Configure Apache
  28. Мониторинг приложения Monitor the app
  29. Создание файла службы Create the service file
  30. Просмотр журналов View logs
  31. Защита данных Data protection
  32. Защита приложения Secure the app
  33. Настройка брандмауэра Configure firewall
  34. Конфигурация HTTPS HTTPS configuration
  35. Дополнительные предложения Apache Additional Apache suggestions
  36. Перезапуск приложений после обновления общей платформы Restart apps with shared framework updates
  37. Дополнительные заголовки Additional headers
  38. Защита Apache от атак кликджекинга Secure Apache from clickjacking attacks
  39. Сканирование типа MIME MIME-type sniffing
  40. Балансировка нагрузки Load Balancing
  41. Ограничения скорости Rate Limits
  42. Длинные поля заголовка запроса Long request header fields

Установка пакета SDK для .NET или среды выполнения .NET вручную Install the .NET SDK or the .NET Runtime manually

Платформа .NET поддерживается в Linux. В этой статье описывается установка .NET в Linux с помощью скрипта установки или посредством извлечения двоичных файлов. .NET is supported on Linux and this article describes how to install .NET on Linux using the install script or by extracting the binaries. Список дистрибутивов, поддерживающих встроенный диспетчер пакетов, см. в разделе Установка .NET в Linux. For a list of distributions that support the built-in package manager, see Install .NET on Linux.

Также можно установить .NET с помощью пакета Snap. You can also install .NET with snap. Дополнительные сведения см. в разделе Установка пакета SDK для .NET или среды выполнения .NET с использованием пакета Snap. For more information, see Install the .NET SDK or the .NET Runtime with Snap.

Если вы хотите разрабатывать приложения .NET, установите пакет SDK (включает среду выполнения). Install the SDK (which includes the runtime) if you want to develop .NET apps. Если нужно просто запустить приложения, установите среду выполнения. Or, if you only need to run apps, install the Runtime. Если вы устанавливаете среду выполнения, мы рекомендуем установить среду выполнения ASP.NET Core, так как она включает в себя среды выполнения .NET и ASP.NET Core. If you’re installing the Runtime, we suggest you install the ASP.NET Core Runtime as it includes both .NET and ASP.NET Core runtimes.

Если вы уже установили пакет SDK или среду выполнения, с помощью команд dotnet —list-sdks и dotnet —list-runtimes узнайте, какие версии установлены. If you’ve already installed the SDK or Runtime, use the dotnet —list-sdks and dotnet —list-runtimes commands to see which versions are installed. Дополнительные сведения см. в статье Проверка того, установлена ли платформа .NET. For more information, see How to check that .NET is already installed.

Выпуски .NET .NET releases

В следующей таблице перечислены выпуски .NET (и .NET Core): The following table lists the .NET (and .NET Core) releases:

✔️ Поддерживается ✔️ Supported ❌ Не поддерживается ❌ Unsupported
5,0 5.0 3.0 3.0
3.1 (LTS) 3.1 (LTS) 2.2 2.2
2.1 (LTS) 2.1 (LTS) 2,0 2.0
1,1 1.1
1.0 1.0

Дополнительные сведения о жизненном цикле выпусков .NET см. в разделе Политика поддержки .NET Core и .NET 5. For more information about the life cycle of .NET releases, see .NET Core and .NET 5 Support Policy.

Зависимости Dependencies

В некоторых случаях, например при установке .NET вручную, некоторые зависимости могут не устанавливаться. It’s possible that when you install .NET, specific dependencies may not be installed, such as when manually installing. Ниже перечислены дистрибутивы Linux, которые поддерживаются корпорацией Майкрософт и для которых может потребоваться установка зависимостей. The following list details Linux distributions that are supported by Microsoft and have dependencies you may need to install. Дополнительные сведения см. на странице, посвященной соответствующему дистрибутиву: Check the distribution page for more information:

Общие сведения о зависимостях см. в статье об автономных приложениях Linux. For generic information about the dependencies, see Self-contained Linux apps.

Зависимости RPM RPM dependencies

Если ваш дистрибутив не указан в приведенном выше списке и построен на основе RPM, могут потребоваться следующие зависимости: If your distribution wasn’t previously listed, and is RPM-based, you may need the following dependencies:

  • krb5-libs krb5-libs
  • libicu libicu
  • openssl-libs openssl-libs

Если в целевой среде выполнения установлена версия OpenSSL 1.1 или более поздняя, необходимо установить compat-openssl10. If the target runtime environment’s OpenSSL version is 1.1 or newer, you’ll need to install compat-openssl10.

Зависимости DEB DEB dependencies

Если ваш дистрибутив не указан в приведенном выше списке и построен на основе Debian, могут потребоваться следующие зависимости: If your distribution wasn’t previously listed, and is debian-based, you may need the following dependencies:

  • libc6 libc6
  • libgcc1 libgcc1
  • libgssapi-krb5-2 libgssapi-krb5-2
  • libicu67 libicu67
  • libssl1.1 libssl1.1
  • libstdc++6 libstdc++6
  • zlib1g zlib1g

Общие зависимости Common dependencies

Для приложений .NET, использующих сборку System.Drawing.Common, необходима также следующая зависимость: For .NET apps that use the System.Drawing.Common assembly, you’ll also need the following dependency:

Вы можете установить последнюю версию libgdiplus, добавив в систему репозиторий Mono. You can install a recent version of libgdiplus by adding the Mono repository to your system. Для получения дополнительной информации см. https://www.mono-project.com/download/stable/. For more information, see https://www.mono-project.com/download/stable/.

Установка с помощью скрипта Scripted install

Сценарии dotnet-install используются для автоматизации установок пакета SDK и среды выполнения и осуществления таких установок без прав администратора. The dotnet-install scripts are used for automation and non-admin installs of the SDK and Runtime. Скрипт можно скачать на странице https://dot.net/v1/dotnet-install.sh. You can download the script from https://dot.net/v1/dotnet-install.sh.

![ВАЖНО] Для выполнения скрипта требуется Bash. ![IMPORTANT] Bash is required to run the script.

Этот сценарий по умолчанию устанавливает последнюю версию SDK с долгосрочной поддержкой (LTS), которой сейчас является .NET Core 3.1. The script defaults to installing the latest SDK long term support (LTS) version, which is .NET Core 3.1. Чтобы установить текущий выпуск, который может не быть версией LTS, используйте параметр -c Current . To install the current release, which may not be an (LTS) version, use the -c Current parameter.

Чтобы вместо пакета SDK установить среду выполнения .NET, используйте параметр —runtime . To install .NET Runtime instead of the SDK, use the —runtime parameter.

Вы можете установить определенную версию, указав ее в параметре -c . You can install a specific version by altering the -c parameter to indicate the specific version. Следующая команда устанавливает пакет SDK для .NET 5.0. The following command installs .NET SDK 5.0.

Установка вручную Manual install

В качестве альтернативы диспетчерам пакетов можно скачать и вручную установить пакет SDK и среду выполнения. As an alternative to the package managers, you can download and manually install the SDK and runtime. Ручная установка как правило выполняется в рамках тестирования непрерывной интеграции или в неподдерживаемом дистрибутиве Linux. Manual install is commonly used as part of continuous integration testing or on an unsupported Linux distribution. В большинстве случаев разработчикам и пользователям рекомендуется использовать диспетчер пакетов. For a developer or user, it’s better to use a package manager.

При установке пакета SDK для .NET не нужно устанавливать соответствующую среду выполнения. If you install .NET SDK, you don’t need to install the corresponding runtime. Сначала скачайте двоичный выпуск пакета SDK или среды выполнения с одного из следующих сайтов: First, download a binary release for either the SDK or the runtime from one of the following sites:

Извлеките скачанный файл и используйте команду export , чтобы задать переменные, используемые .NET, а затем проверьте включение .NET в переменную PATH. Next, extract the downloaded file and use the export command to set variables used by .NET and then ensure .NET is in PATH.

Чтобы извлечь среду выполнения и сделать команды .NET CLI доступными в терминале, сначала скачайте двоичный выпуск .NET. To extract the runtime and make the .NET CLI commands available at the terminal, first download a .NET binary release. Затем откройте терминал и выполните следующие команды в каталоге с сохраненным файлом. Then, open a terminal and run the following commands from the directory where the file was saved. Имя файла архива может отличаться в зависимости от скачанных файлов. The archive file name may be different depending on what you downloaded.

Используйте следующие команды для извлечения скачанной среды выполнения или пакета SDK. Use the following commands to extract the runtime or SDK that you downloaded. Не забудьте заменить значение DOTNET_FILE на имя файла: Remember to change the DOTNET_FILE value to your file name:

Приведенные выше команды export сделают команды .NET CLI доступными только для сеанса терминала, в котором производился запуск. The preceding export commands only make the .NET CLI commands available for the terminal session in which it was run.

Вы можете изменить профиль оболочки, чтобы добавить команды окончательно. You can edit your shell profile to permanently add the commands. Существует несколько различных оболочек, доступных для Linux, и каждая из них имеет свой профиль. There are a number of different shells available for Linux and each has a different profile. Пример: For example:

    Оболочка Bash:

/.bashrc Bash Shell:

/.bashrc
Оболочка Korn:

/.kshrc или .profile Korn Shell:

/.kshrc or .profile
Оболочка Z:

/.zshrc или .zprofile Z Shell:

Измените соответствующий исходный файл оболочки и добавьте :$HOME/dotnet в конец существующего оператора PATH . Edit the appropriate source file for your shell and add :$HOME/dotnet to the end of the existing PATH statement. Если оператор PATH не указан, добавьте новую строку с export PATH=$PATH:$HOME/dotnet . If no PATH statement is included, add a new line with export PATH=$PATH:$HOME/dotnet .

Кроме того, добавьте export DOTNET_ROOT=$HOME/dotnet в конец файла. Also, add export DOTNET_ROOT=$HOME/dotnet to the end of the file.

Такой подход позволяет устанавливать разные версии в отдельные расположения и выбирать, какие из них следует использовать для каждого приложения. This approach lets you install different versions into separate locations and choose explicitly which one to use by which application.

Download .NET

Downloads for .NET Framework and .NET Core, including ASP.NET and ASP.NET Core

Not sure where to start? See the Hello World in 10 minutes tutorial to install .NET and build your first app.

.NET is a free, cross-platform, open-source developer platform for building many different types of applications.

.NET Core 3.1

.NET Core is a free, cross-platform, open-source developer platform for building many different types of applications.

.NET Framework 4.8

.NET Framework is a Windows-only version of .NET for building any type of app that runs on Windows.

.NET is a free, cross-platform, open-source developer platform for building many different types of applications.

.NET Core 3.1

.NET Core is a free, cross-platform, open-source developer platform for building many different types of applications.

.NET is a free, cross-platform, open-source developer platform for building many different types of applications.

.NET Core 3.1

.NET Core is a free, cross-platform, open-source developer platform for building many different types of applications.

.NET is a free, cross-platform, open-source developer platform for building many different types of applications.

.NET Core

.NET Core is a free, cross-platform, open-source developer platform for building many different types of applications.

.NET Framework

.NET Framework is a Windows-only version of .NET for building any type of app that runs on Windows.

Free. Cross-platform. Open source. Supported.

.NET is free. There are no fees or licensing costs, including for commercial use.

.NET is open-source and cross-platform, with free development tools for Linux, Windows, and macOS.

.NET is supported by Microsoft. Microsoft ships official releases that are built and tested on Microsoft-maintained servers in Azure and supported just like any Microsoft product.

Thank You to All the Contributors

.NET is open source and we are very thankful for the many contributions it receives from the community.

Ready to Get Started?

Our step-by-step tutorial will help you get .NET running on your computer.

Размещение ASP.NET Core в операционной системе Linux с Apache Host ASP.NET Core on Linux with Apache

Из этого руководства вы узнаете, как настроить Apache в качестве обратного прокси-сервера в CentOS 7 для перенаправления трафика HTTP в веб-приложение ASP.NET Core, выполняемое на сервере Kestrel. Using this guide, learn how to set up Apache as a reverse proxy server on CentOS 7 to redirect HTTP traffic to an ASP.NET Core web app running on Kestrel server. Расширение mod_proxy и связанные с ним модули создают обратный прокси-сервер. The mod_proxy extension and related modules create the server’s reverse proxy.

Предварительные требования Prerequisites

  • Сервер под управлением CentOS 7 и учетная запись обычного пользователя с правами sudo. Server running CentOS 7 with a standard user account with sudo privilege.
  • Установите среду выполнения .NET Core на сервере. Install the .NET Core runtime on the server.
    1. Перейдите на страницу скачивания .NET Core. Visit the Download .NET Core page.
    2. Выберите последнюю не предварительную версию .NET Core. Select the latest non-preview .NET Core version.
    3. Скачайте последнюю не предварительную версию среды выполнения из таблицы под заголовком Run apps — Runtime (Выполнение приложений — среда выполнения). Download the latest non-preview runtime in the table under Run apps — Runtime.
    4. Щелкните ссылку Package manager instructions (Инструкции диспетчера пакетов) для Linux и выполните инструкции для CentOS. Select the Linux Package manager instructions link and follow the CentOS instructions.
  • Существующее приложение ASP.NET Core. An existing ASP.NET Core app.

Перезапустить приложения ASP.NET Core, размещенные на сервере, можно в любой момент после обновления общей платформы. At any point in the future after upgrading the shared framework, restart the ASP.NET Core apps hosted by the server.

Публикация и копирование приложения Publish and copy over the app

Если приложение запускается локально и не настроено для безопасного подключения (HTTPS), следует применять один из следующих подходов. If the app is run locally and isn’t configured to make secure connections (HTTPS), adopt either of the following approaches:

  • Настройка приложения для обработки безопасных локальных подключений. Configure the app to handle secure local connections. Дополнительные сведения см. в разделе Конфигурация HTTPS. For more information, see the HTTPS configuration section.
  • Удалите https://localhost:5001 (при его наличии) из свойства applicationUrl в файле Properties/launchSettings.json. Remove https://localhost:5001 (if present) from the applicationUrl property in the Properties/launchSettings.json file.

Запустите dotnet publish в среде разработки, чтобы упаковать приложение в каталог (например, bin/Release/ /publish), который может выполняться на сервере: Run dotnet publish from the development environment to package an app into a directory (for example, bin/Release/ /publish) that can run on the server:

Приложение может быть опубликовано как автономное развертывание, если вы предпочитаете не сохранять среду выполнения .NET Core на сервере. The app can also be published as a self-contained deployment if you prefer not to maintain the .NET Core runtime on the server.

Скопируйте приложение ASP.NET Core на сервер с помощью инструмента, интегрированного в ваш рабочий процесс (например, SCP или SFTP). Copy the ASP.NET Core app to the server using a tool that integrates into the organization’s workflow (for example, SCP, SFTP). Обычно веб-приложения находятся в каталоге var (например, var/www/helloapp). It’s common to locate web apps under the var directory (for example, var/www/helloapp).

Если развертывание выполняется в рабочей среде, рабочий процесс непрерывной интеграции автоматически опубликует приложение и скопирует его ресурсы на сервер. Under a production deployment scenario, a continuous integration workflow does the work of publishing the app and copying the assets to the server.

Настройка прокси-сервера Configure a proxy server

Обратный прокси-сервер — это стандартный вариант настройки для обслуживания динамических веб-приложений. A reverse proxy is a common setup for serving dynamic web apps. Обратный прокси-сервер завершает HTTP-запрос и перенаправляет его в приложение ASP.NET. The reverse proxy terminates the HTTP request and forwards it to the ASP.NET app.

Прокси-сервер перенаправляет запросы клиента на другой сервер, а не обрабатывает их самостоятельно. A proxy server forwards client requests to another server instead of fulfilling requests itself. Обратный прокси-сервер перенаправляет запросы в фиксированное назначение обычно от имени клиентов. A reverse proxy forwards to a fixed destination, typically on behalf of arbitrary clients. При работе с этим руководством мы настроим Apache в качестве обратного прокси-сервера, который работает на том же сервере, где Kestrel предоставляет приложение ASP.NET Core. In this guide, Apache is configured as the reverse proxy running on the same server that Kestrel is serving the ASP.NET Core app.

Так как запросы перенаправляются обратным прокси-сервером, используйте ПО промежуточного слоя перенаправления заголовков, которое входит в пакет Microsoft.AspNetCore.HttpOverrides. Because requests are forwarded by reverse proxy, use the Forwarded Headers Middleware from the Microsoft.AspNetCore.HttpOverrides package. Это ПО обновляет Request.Scheme , используя заголовок X-Forwarded-Proto , что обеспечивает правильную работу URI перенаправления и других политик безопасности. The middleware updates the Request.Scheme , using the X-Forwarded-Proto header, so that redirect URIs and other security policies work correctly.

Любой компонент, который зависит от схемы, например проверка подлинности, генерация ссылок, перенаправление и геолокация, должен находиться после вызова ПО промежуточного слоя перенаправления заголовков. Any component that depends on the scheme, such as authentication, link generation, redirects, and geolocation, must be placed after invoking the Forwarded Headers Middleware.

ПО промежуточного слоя перенаправления заголовков должно выполняться до другого ПО промежуточного слоя. Forwarded Headers Middleware should run before other middleware. Такой порядок гарантирует, что ПО промежуточного слоя, полагающееся на сведения о перенаправленных заголовках, может использовать значения заголовков для обработки. This ordering ensures that the middleware relying on forwarded headers information can consume the header values for processing. Сведения о запуске ПО промежуточного слоя перенаправления заголовков после ПО промежуточного слоя диагностики и обработки ошибок см. в разделе Порядок ПО промежуточного слоя перенаправления заголовков. To run Forwarded Headers Middleware after diagnostics and error handling middleware, see Forwarded Headers Middleware order.

Вызовите UseForwardedHeaders метод наверху Startup.Configure , прежде чем вызывать другое ПО промежуточного слоя. Invoke the UseForwardedHeaders method at the top of Startup.Configure before calling other middleware. В ПО промежуточного слоя настройте перенаправление заголовков X-Forwarded-For и X-Forwarded-Proto : Configure the middleware to forward the X-Forwarded-For and X-Forwarded-Proto headers:

Если параметр ForwardedHeadersOptions не задан для ПО промежуточного слоя, по умолчанию перенаправляются заголовки None . If no ForwardedHeadersOptions are specified to the middleware, the default headers to forward are None .

Прокси-серверы под управлением петлевых адресов ( 127.0.0.0/8, [::1] ), включая стандартные адреса localhost (127.0.0.1), считаются доверенными по умолчанию. Proxies running on loopback addresses ( 127.0.0.0/8, [::1] ), including the standard localhost address (127.0.0.1), are trusted by default. Если запросы между Интернетом и веб-сервером обрабатывают другие прокси-серверы или сети организации, добавьте их в список KnownProxies или KnownNetworks с помощью ForwardedHeadersOptions. If other trusted proxies or networks within the organization handle requests between the Internet and the web server, add them to the list of KnownProxies or KnownNetworks with ForwardedHeadersOptions. Следующий пример добавляет доверенный прокси-сервер с IP-адресом 10.0.0.100 в ПО промежуточного слоя для перенаправления заголовков KnownProxies в Startup.ConfigureServices : The following example adds a trusted proxy server at IP address 10.0.0.100 to the Forwarded Headers Middleware KnownProxies in Startup.ConfigureServices :

Установка Apache Install Apache

Обновите пакеты CentOS до последних стабильных версий: Update CentOS packages to their latest stable versions:

Установите веб-сервер Apache на CentOS, выполнив одну команду yum : Install the Apache web server on CentOS with a single yum command:

Пример выходных данных этой команды: Sample output after running the command:

В нашем примере выходные данные содержат строку httpd.86_64, так как используется 64-разрядная версия CentOS 7. In this example, the output reflects httpd.86_64 since the CentOS 7 version is 64 bit. Чтобы проверить, где установлен Apache, выполните whereis httpd из командной строки. To verify where Apache is installed, run whereis httpd from a command prompt.

Настройка Apache Configure Apache

Файлы конфигурации для Apache находятся в каталоге /etc/httpd/conf.d/ . Configuration files for Apache are located within the /etc/httpd/conf.d/ directory. В алфавитном порядке обрабатываются все файлы с расширением .conf, а также файлы конфигурации модуля из папки /etc/httpd/conf.modules.d/ , где содержатся файлы конфигурации, необходимые для загрузки модулей. Any file with the .conf extension is processed in alphabetical order in addition to the module configuration files in /etc/httpd/conf.modules.d/ , which contains any configuration files necessary to load modules.

Создайте для приложения файл конфигурации с именем helloapp.conf: Create a configuration file, named helloapp.conf, for the app:

Блок VirtualHost может встречаться несколько раз в одном или нескольких файлах на сервере. The VirtualHost block can appear multiple times, in one or more files on a server. С представленным выше файлом конфигурации Apache принимает трафик от любого источника через порт 80. In the preceding configuration file, Apache accepts public traffic on port 80. Он обслуживает домен www.example.com , а псевдоним *.example.com указывает на тот же веб-сайт. The domain www.example.com is being served, and the *.example.com alias resolves to the same website. Дополнительные сведения см. в статье о поддержке виртуальных узлов на основе имен. For more information, see Name-based virtual host support. Запросы к корневому каталогу перенаправляются на порт 5000 того же сервера по адресу 127.0.0.1. Requests are proxied at the root to port 5000 of the server at 127.0.0.1. Для двусторонней связи требуются ProxyPass и ProxyPassReverse . For bi-directional communication, ProxyPass and ProxyPassReverse are required. Сведения о том, как изменить IP-адрес/порт Kestrel, см. в разделе Kestrel: конфигурация конечной точки. To change Kestrel’s IP/port, see Kestrel: Endpoint configuration.

Блок VirtualHost может встречаться несколько раз в одном или нескольких файлах на сервере. The VirtualHost block can appear multiple times, in one or more files on a server. С представленным выше файлом конфигурации Apache принимает трафик от любого источника через порт 80. In the preceding configuration file, Apache accepts public traffic on port 80. Он обслуживает домен www.example.com , а псевдоним *.example.com указывает на тот же веб-сайт. The domain www.example.com is being served, and the *.example.com alias resolves to the same website. Дополнительные сведения см. в статье о поддержке виртуальных узлов на основе имен. For more information, see Name-based virtual host support. Запросы к корневому каталогу перенаправляются на порт 5000 того же сервера по адресу 127.0.0.1. Requests are proxied at the root to port 5000 of the server at 127.0.0.1. Для двусторонней связи требуются ProxyPass и ProxyPassReverse . For bi-directional communication, ProxyPass and ProxyPassReverse are required. Сведения о том, как изменить IP-адрес/порт Kestrel, см. в разделе Kestrel: конфигурация конечной точки. To change Kestrel’s IP/port, see Kestrel: Endpoint configuration.

Если не удастся указать правильную директиву ServerName в блоке VirtualHost, приложение будет иметь значительные уязвимости. Failure to specify a proper ServerName directive in the VirtualHost block exposes your app to security vulnerabilities. Привязки с подстановочными знаками на уровне дочерних доменов (например, *.example.com ) не создают таких угроз безопасности, если вы полностью контролируете родительский домен (в отличие от варианта *.com , создающего уязвимость). Subdomain wildcard binding (for example, *.example.com ) doesn’t pose this security risk if you control the entire parent domain (as opposed to *.com , which is vulnerable). Дополнительные сведения см. в документе rfc7230, раздел 5.4. For more information, see rfc7230 section-5.4.

Ведение журнала можно настроить отдельно для каждого VirtualHost с помощью директив ErrorLog и CustomLog . Logging can be configured per VirtualHost using ErrorLog and CustomLog directives. Журналы ошибок сохраняются в расположение ErrorLog , а параметр CustomLog задает имя и формат для файла журнала. ErrorLog is the location where the server logs errors, and CustomLog sets the filename and format of log file. В нашем примере здесь фиксируются сведения о запросах. In this case, this is where request information is logged. Для каждого запроса создается одна строка. There’s one line for each request.

Сохраните файл и протестируйте конфигурацию. Save the file and test the configuration. Если проверка выполнена успешно, ответ должен быть Syntax [OK] . If everything passes, the response should be Syntax [OK] .

Перезапустите Apache. Restart Apache:

Мониторинг приложения Monitor the app

Теперь Apache настроен на перенаправление запросов к http://localhost:80 в приложение ASP.NET Core, выполняемое в Kestrel по адресу http://127.0.0.1:5000 . Apache is now set up to forward requests made to http://localhost:80 to the ASP.NET Core app running on Kestrel at http://127.0.0.1:5000 . Но Apache не настроен для управления процессом Kestrel. However, Apache isn’t set up to manage the Kestrel process. Для запуска и мониторинга базового веб-приложения используйте systemd и создайте файл службы. Use systemd and create a service file to start and monitor the underlying web app. systemd — это система инициализации, предоставляющая различные функции для запуска и остановки процессов, а также управления ими. systemd is an init system that provides many powerful features for starting, stopping, and managing processes.

Создание файла службы Create the service file

Создайте файл определения службы. Create the service definition file:

Пример файла службы для приложения: An example service file for the app:

В предыдущем примере управляющий службой пользователь задается с помощью параметра User . In the preceding example, the user that manages the service is specified by the User option. Этот пользователь ( apache ) должен существовать и иметь права владельца в отношении файлов приложения. The user ( apache ) must exist and have proper ownership of the app’s files.

Используйте TimeoutStopSec , чтобы настроить время ожидания до завершения работы приложения после начального сигнала прерывания. Use TimeoutStopSec to configure the duration of time to wait for the app to shut down after it receives the initial interrupt signal. Если приложение не завершит работу в течение этого периода, оно прерывается сигналом SIGKILL. If the app doesn’t shut down in this period, SIGKILL is issued to terminate the app. Укажите значение в секундах без единиц измерения (например, 150 ), значение интервала (например, 2min 30s ) или значение infinity , которое отключает время ожидания. Provide the value as unitless seconds (for example, 150 ), a time span value (for example, 2min 30s ), or infinity to disable the timeout. По умолчанию TimeoutStopSec принимает значение DefaultTimeoutStopSec в файле конфигурации диспетчера (systemd-system.conf, system.conf.d, systemd-user.conf, user.conf.d). TimeoutStopSec defaults to the value of DefaultTimeoutStopSec in the manager configuration file (systemd-system.conf, system.conf.d, systemd-user.conf, user.conf.d). В большинстве дистрибутивов по умолчанию устанавливается время ожидания 90 секунд. The default timeout for most distributions is 90 seconds.

Некоторые значения (например, строки подключения SQL) необходимо экранировать, чтобы поставщики конфигурации могли считать переменные среды. Some values (for example, SQL connection strings) must be escaped for the configuration providers to read the environment variables. Используйте следующую команду, чтобы создать правильно экранированное значение для файла конфигурации: Use the following command to generate a properly escaped value for use in the configuration file:

Разделители-двоеточия ( : ) не поддерживаются в именах переменных среды. Colon ( : ) separators aren’t supported in environment variable names. Следует использовать двойной знак подчеркивания ( __ ) вместо двоеточия. Use a double underscore ( __ ) in place of a colon. Поставщик конфигурации переменных среды преобразует двойные символы подчеркивания в двоеточия, когда переменные среды считываются в конфигурации. The Environment Variables configuration provider converts double-underscores into colons when environment variables are read into configuration. В следующем примере ключ строки подключения ConnectionStrings:DefaultConnection задается в файле определения службы как ConnectionStrings__DefaultConnection . In the following example, the connection string key ConnectionStrings:DefaultConnection is set into the service definition file as ConnectionStrings__DefaultConnection :

Разделители-двоеточия ( : ) не поддерживаются в именах переменных среды. Colon ( : ) separators aren’t supported in environment variable names. Следует использовать двойной знак подчеркивания ( __ ) вместо двоеточия. Use a double underscore ( __ ) in place of a colon. Поставщик конфигурации переменных среды преобразует двойные символы подчеркивания в двоеточия, когда переменные среды считываются в конфигурации. The Environment Variables configuration provider converts double-underscores into colons when environment variables are read into configuration. В следующем примере ключ строки подключения ConnectionStrings:DefaultConnection задается в файле определения службы как ConnectionStrings__DefaultConnection . In the following example, the connection string key ConnectionStrings:DefaultConnection is set into the service definition file as ConnectionStrings__DefaultConnection :

Сохраните файл и включите службу. Save the file and enable the service:

Запустите службу и убедитесь, что она работает. Start the service and verify that it’s running:

Теперь, когда обратный прокси-сервер настроен и systemd управляет процессом Kestrel, веб-приложение можно считать полностью настроенным и вы можете обратиться к нему по адресу http://localhost из браузера на локальном компьютере. With the reverse proxy configured and Kestrel managed through systemd, the web app is fully configured and can be accessed from a browser on the local machine at http://localhost . Заголовок Server в ответе подтверждает, что приложение ASP.NET Core обслуживается Kestrel. Inspecting the response headers, the Server header indicates that the ASP.NET Core app is served by Kestrel:

Просмотр журналов View logs

Так как веб-приложением, использующим Kestrel, управляет systemd, все события и процессы регистрируются в централизованном журнале. Since the web app using Kestrel is managed using systemd, events and processes are logged to a centralized journal. Но этот журнал содержит все записи обо всех службах и процессах, управляемых systemd. However, this journal includes entries for all of the services and processes managed by systemd. Чтобы просмотреть элементы, связанные с kestrel-helloapp.service , используйте следующую команду. To view the kestrel-helloapp.service -specific items, use the following command:

Чтобы отфильтровать элементы по времени, укажите в команде параметры времени. For time filtering, specify time options with the command. Например, —since today позволяет отфильтровать данные за текущий день, а —until 1 hour ago — просмотреть записи за предыдущий час. For example, use —since today to filter for the current day or —until 1 hour ago to see the previous hour’s entries. Дополнительные сведения см. на странице руководства о команде journalctl. For more information, see the man page for journalctl.

Защита данных Data protection

Стек защиты данных в ASP.NET Core используется определенным ПО промежуточного слоя ASP.NET Core, включая промежуточное ПО для проверки подлинности (например, промежуточное ПО файлов cookie) и средствами защиты от подделки межсайтовых запросов. The ASP.NET Core Data Protection stack is used by several ASP.NET Core middlewares, including authentication middleware (for example, cookie middleware) and cross-site request forgery (CSRF) protections. Даже если API-интерфейсы защиты данных не вызываются из пользовательского кода, необходимо настроить защиту данных для создания постоянного хранилища криптографических ключей. Even if Data Protection APIs aren’t called by user code, data protection should be configured to create a persistent cryptographic key store. Если защита данных не настроена, ключи хранятся в памяти и удаляются при перезапуске приложения. If data protection isn’t configured, the keys are held in memory and discarded when the app restarts.

Если набор ключей хранится в памяти, при перезапуске приложения происходит следующее: If the key ring is stored in memory when the app restarts:

  • Все токены аутентификации, использующие файлы cookie, становятся недействительными. All cookie-based authentication tokens are invalidated.
  • При выполнении следующего запроса пользователю требуется выполнить вход снова. Users are required to sign in again on their next request.
  • Все данные, защищенные с помощью набора ключей, больше не могут быть расшифрованы. Any data protected with the key ring can no longer be decrypted. Это могут быть токены CSRF и файлы cookie временных данных ASP.NET Core MVC. This may include CSRF tokens and ASP.NET Core MVC TempData cookies.

Сведения о настройке защиты данных для хранения и шифрования набора ключей см. в приведенных ниже статьях. To configure data protection to persist and encrypt the key ring, see:

Защита приложения Secure the app

Настройка брандмауэра Configure firewall

Firewalld — это динамическая управляющая программа брандмауэра, которая поддерживает зоны сети. Firewalld is a dynamic daemon to manage the firewall with support for network zones. Фильтрацию портов и пакетов можно по-прежнему осуществлять через iptables. Ports and packet filtering can still be managed by iptables. Firewalld обычно устанавливается в системе по умолчанию. Firewalld should be installed by default. yum позволяет установить этот пакет или убедиться, что он установлен. yum can be used to install the package or verify it’s installed.

С помощью firewalld вы можете открыть только те порты, которые необходимые для работы приложения. Use firewalld to open only the ports needed for the app. В этом случае используются порты 80 и 443. In this case, ports 80 and 443 are used. Следующие команды назначают порты 80 и 443 постоянно открытыми. The following commands permanently set ports 80 and 443 to open:

Обновите параметры брандмауэра. Reload the firewall settings. Проверьте, что доступные службы и порты находятся в зоне по умолчанию. Check the available services and ports in the default zone. Эти параметры можно просмотреть с помощью firewall-cmd -h . Options are available by inspecting firewall-cmd -h .

Конфигурация HTTPS HTTPS configuration

Настройка приложения для безопасных (HTTPS) локальных подключений Configure the app for secure (HTTPS) local connections

Команда dotnet run использует файл приложения Properties/launchSettings.json, который настраивает приложение для прослушивания URL-адресов, заданных свойством applicationUrl (например, https://localhost:5001;http://localhost:5000 ). The dotnet run command uses the app’s Properties/launchSettings.json file, which configures the app to listen on the URLs provided by the applicationUrl property (for example, https://localhost:5001;http://localhost:5000 ).

Настройте приложение для использования при разработке сертификата для команды dotnet run или среды разработки (F5 или CTRL + F5 в Visual Studio Code), используя один из следующих подходов. Configure the app to use a certificate in development for the dotnet run command or development environment (F5 or Ctrl+F5 in Visual Studio Code) using one of the following approaches:

Настройка обратного прокси-сервера для безопасного подключения клиентов (HTTPS) Configure the reverse proxy for secure (HTTPS) client connections

Конфигурация безопасности в этом разделе представляет собой общую конфигурацию, которая будет использоваться в качестве отправной точки для дальнейшей настройки. The security configuration in this section is a general configuration to be used as a starting point for further customization. Мы не можем обеспечить поддержку инструментов, серверов и операционных систем сторонних производителей. We’re unable to provide support for third-party tooling, servers, and operating systems. Ответственность за использование конфигурации в этом разделе лежит на пользователе. Use the configuration in this section at your own risk. Дополнительные сведения см. в следующих ресурсах: For more information, access the following resources:

  • Шифрование Apache SSL/TLS (документация по Apache) Apache SSL/TLS Encryption (Apache documentation)
  • mozilla.org SSL Configuration Generator mozilla.org SSL Configuration Generator

Apache для HTTPS настраивается с помощью модуля mod_ssl. To configure Apache for HTTPS, the mod_ssl module is used. При установке модуля httpd автоматически добавляется и модуль mod_ssl. When the httpd module was installed, the mod_ssl module was also installed. Если он по каким-то причинам отсутствует, добавьте его в систему с помощью yum . If it wasn’t installed, use yum to add it to the configuration.

Чтобы принудительно использовать HTTPS, установите модуль mod_rewrite для перезаписи URL-адресов: To enforce HTTPS, install the mod_rewrite module to enable URL rewriting:

Измените файл helloapp.conf, чтобы разрешить безопасный обмен данными через порт 443. Modify the helloapp.conf file to enable secure communication on port 443.

В следующем примере не выполняется настройка сервера для перенаправления небезопасных запросов. The following example doesn’t configure the server to redirect insecure requests. Рекомендуется использовать ПО промежуточного слоя перенаправления HTTPS. We recommend using HTTPS Redirection Middleware. Для получения дополнительной информации см. Принудительное применение HTTPS в ASP.NET Core. For more information, see Принудительное применение HTTPS в ASP.NET Core.

Для сред разработки, в которых безопасное перенаправление обрабатывается конфигурацией сервера, а не ПО промежуточного слоя перенаправления HTTPS, рекомендуется использовать временные перенаправления (302), а не постоянные перенаправления (301). For development environments where the server configuration handles secure redirection instead of HTTPS Redirection Middleware, we recommend using temporary redirects (302) rather than permanent redirects (301). Кэширование ссылок может привести к нестабильной работе в средах разработки. Link caching can cause unstable behavior in development environments.

При добавлении заголовка Strict-Transport-Security (HSTS) все последующие запросы клиента будут проходить по протоколу HTTPS. Adding a Strict-Transport-Security (HSTS) header ensures all subsequent requests made by the client are over HTTPS. Рекомендации по настройке заголовка Strict-Transport-Security см. в разделе Принудительное применение HTTPS в ASP.NET Core. For guidance on setting the Strict-Transport-Security header, see Принудительное применение HTTPS в ASP.NET Core.

В этом примере используется локально созданный сертификат. This example is using a locally-generated certificate. В SSLCertificateFile должен быть указан основной файл сертификата для доменного имени. SSLCertificateFile should be the primary certificate file for the domain name. В SSLCertificateKeyFile должен быть указан файл ключа, сформированный при создании CSR. SSLCertificateKeyFile should be the key file generated when CSR is created. В SSLCertificateChainFile должен быть указан файл промежуточного сертификата (если он существует), предоставленный центром сертификации. SSLCertificateChainFile should be the intermediate certificate file (if any) that was supplied by the certificate authority.

Для работы с веб-сервером TLS 1.3 с OpenSSL 1.1.1 требуется сервер Apache HTTP Apache 2.4.43 или более поздней версии. Apache HTTP Server version 2.4.43 or newer is required in order to operate a TLS 1.3 web server with OpenSSL 1.1.1.

[Примечание] В предыдущем примере ассоциация протокола OCSP отключена. [NOTE] The preceding example disables Online Certificate Status Protocol (OCSP) Stapling. Дополнительные сведения и рекомендации по включению OCSP см. в разделе об ассоциации OCSP (документация по Apache). For more information and guidance on enabling OCSP, see OCSP Stapling (Apache documentation).

Сохраните файл и протестируйте конфигурацию. Save the file and test the configuration:

Перезапустите Apache. Restart Apache:

Дополнительные предложения Apache Additional Apache suggestions

Перезапуск приложений после обновления общей платформы Restart apps with shared framework updates

После обновления общей платформы на сервере перезапустите размещенные на нем приложения ASP.NET Core. After upgrading the shared framework on the server, restart the ASP.NET Core apps hosted by the server.

Дополнительные заголовки Additional headers

Для защиты от вредоносных атак следует изменить или добавить несколько заголовков. To secure against malicious attacks, there are a few headers that should either be modified or added. Убедитесь, что модуль mod_headers установлен. Ensure that the mod_headers module is installed:

Защита Apache от атак кликджекинга Secure Apache from clickjacking attacks

Кликджекинг (или атака с подменой пользовательского интерфейса) является вредоносной атакой, при которой посетителя сайта обманным путем вынуждают щелкнуть ссылку или нажать кнопку не той страницы, на которой он находится. Clickjacking, also known as a UI redress attack, is a malicious attack where a website visitor is tricked into clicking a link or button on a different page than they’re currently visiting. Используйте X-FRAME-OPTIONS для защиты сайта. Use X-FRAME-OPTIONS to secure the site.

Чтобы уменьшить риск атак кликджекинга, выполните указанные ниже действия. To mitigate clickjacking attacks:

Измените файл httpd.conf. Edit the httpd.conf file:

Добавьте строку Header append X-FRAME-OPTIONS «SAMEORIGIN» . Add the line Header append X-FRAME-OPTIONS «SAMEORIGIN» .

Сохраните файл. Save the file.

Перезапустите Apache. Restart Apache.

Сканирование типа MIME MIME-type sniffing

Заголовок X-Content-Type-Options защищает Internet Explorer от сканирования MIME (определения Content-Type для файла по его содержимому). The X-Content-Type-Options header prevents Internet Explorer from MIME-sniffing (determining a file’s Content-Type from the file’s content). Если сервер задает заголовок Content-Type со значением text/html , и при этом установлен параметр nosniff , Internet Explorer отображает содержимое как text/html независимо от содержимого файла. If the server sets the Content-Type header to text/html with the nosniff option set, Internet Explorer renders the content as text/html regardless of the file’s content.

Измените файл httpd.conf. Edit the httpd.conf file:

Добавьте строку Header set X-Content-Type-Options «nosniff» . Add the line Header set X-Content-Type-Options «nosniff» . Сохраните файл. Save the file. Перезапустите Apache. Restart Apache.

Балансировка нагрузки Load Balancing

В этом примере показано, как установить и настроить Apache в CentOS 7 и Kestrel на том же компьютере. This example shows how to setup and configure Apache on CentOS 7 and Kestrel on the same instance machine. Чтобы устранить единую точку отказа, воспользуйтесь mod_proxy_balancer и измените значение VirtualHost для управления несколькими экземплярами веб-приложений за прокси-сервером Apache. To not have a single point of failure; using mod_proxy_balancer and modifying the VirtualHost would allow for managing multiple instances of the web apps behind the Apache proxy server.

В представленном ниже файле конфигурации настроен дополнительный экземпляр helloapp , работающий на порте 5001. In the configuration file shown below, an additional instance of the helloapp is set up to run on port 5001. В разделе Proxy настраивается конфигурация подсистемы балансировки нагрузки с двумя членами для распределения нагрузки методом byrequests. The Proxy section is set with a balancer configuration with two members to load balance byrequests.

Ограничения скорости Rate Limits

С помощью элемента mod_ratelimit, который входит в модуль httpd, можно ограничить пропускную способность для клиентов: Using mod_ratelimit, which is included in the httpd module, the bandwidth of clients can be limited:

В примере файла пропускная способность составляет 600 Кбит/с в корневой папке. The example file limits bandwidth as 600 KB/sec under the root location:

Длинные поля заголовка запроса Long request header fields

Параметры прокси-сервера по умолчанию обычно ограничивают длину полей заголовка запроса значением 8190 байт. Proxy server default settings typically limit request header fields to 8,190 bytes. Приложению могут потребоваться более длинные поля (например, приложениям, использующим Azure Active Directory). An app may require fields longer than the default (for example, apps that use Azure Active Directory). В этом случае требуется скорректировать директиву LimitRequestFieldSize для прокси-сервера. If longer fields are required, the proxy server’s LimitRequestFieldSize directive requires adjustment. Применяемое значение зависит от конкретного сценария. The value to apply depends on the scenario. Дополнительные сведения см. в документации сервера. For more information, see your server’s documentation.

Не увеличивайте значение LimitRequestFieldSize по умолчанию, если это не требуется. Don’t increase the default value of LimitRequestFieldSize unless necessary. Увеличение значения повышает риск переполнения буфера и атак типа «отказ в обслуживании» (DoS) со стороны злоумышленников. Increasing the value increases the risk of buffer overrun (overflow) and Denial of Service (DoS) attacks by malicious users.

Читайте также:  При подготовке обновления произошла ошибка big sur mac os
Оцените статью