Сервис приложения
Сервисы/ASP.NET Core

Сервис ASP.NET Core

Среда выполнения ASP.NET Core для сборки веб-приложений и API на .NET из исходного кода с необязательными связями с базой данных, кешем и почтой.

Этот сервис запускает ваш код: его образ собирается из Git-репозитория, а каждая сборка развёртывается в окружение.

В StackMaster

Как ASP.NET Core работает в StackMaster

What Wodby sets up for an application that runs on this service. Check it before changing the build, the port or connection settings in the code.

Build and start

The service's Dockerfile publishes the repository with the .NET SDK and runs the result on the service image:

  1. it picks the project: the DOTNET_PROJECT build argument, or else the only project file (*.csproj, *.fsproj, *.vbproj) at the repository's root, or else the only one in a src/<name>/ directory. Among several, it takes the only runnable one: a Microsoft.NET.Sdk.Web or Microsoft.NET.Sdk.Worker project, or one with <OutputType>Exe</OutputType>. Otherwise the build fails;
  2. runs dotnet publish -c Release for it, with RestoreLockedMode when the repository has a packages.lock.json;
  3. copies the output to /usr/src/app in the service image, which has the ASP.NET Core runtime but no SDK.

The container starts dotnet-app, which runs the assembly named by DOTNET_APP, or else the one whose *.runtimeconfig.json is the only one in /usr/src/app. The build stage uses the newest .NET SDK, which also builds projects for earlier .NET versions; the project's TargetFramework must match the service's .NET version. A pipeline that passes a Dockerfile from the repository (wodby ci build dotnet -f Dockerfile) uses that file instead; its final stage must be FROM ${WODBY_BASE_IMAGE}.

  • The application must listen on port 8080, on all interfaces. That is the port of the service's HTTP endpoint and the image's ASPNETCORE_HTTP_PORTS, which ASP.NET Core reads. Do not set URLs in launchSettings.json or code for deployed environments: launchSettings.json is not used by a published application.
  • The service is ready once the port accepts connections.
  • DOTNET_ENVIRONMENT is Development in development environments and unset elsewhere, so applications run as Production.
  • The image has ICU and full culture data; globalization-invariant mode is off.
  • The service declares no volume of its own: files written inside the container are lost when it is replaced. That includes ASP.NET Core Data Protection keys, which by default live in the container's home: cookies and antiforgery tokens stop being valid after a deployment and differ between replicas. Persist the keys to Redis or a database when the application uses them.

Linked services

Links to other services reach the application as environment variables. Nothing in the image reads them: the application reads them itself, for example with NpgsqlConnectionStringBuilder or MySqlConnectionStringBuilder, which quote values correctly. Do not hardcode hosts or credentials.

LinkVariables
Database (MariaDB, MySQL or PostgreSQL)DB_HOST, DB_PORT, DB_NAME, DB_USERNAME, DB_PASSWORD, DB_DRIVER
MailSMTP_HOST, SMTP_PORT
Redis or ValkeyREDIS_HOST, REDIS_PORT, REDIS_PASSWORD
OpenTelemetry CollectorOTEL_EXPORTER_OTLP_ENDPOINT, OTEL_EXPORTER_OTLP_PROTOCOL (http/protobuf), OTEL_EXPORTER_OTLP_HEADERS (the Collector's ingest token)

All links are optional. A variable is present only while its link exists and the linked service is enabled. The mail link carries no credentials. The OpenTelemetry variables are the standard SDK settings: an application or agent that uses an OpenTelemetry SDK exports to the Collector without further configuration; set OTEL_SERVICE_NAME to name the application in traces.

Environment

  • WODBY_HOSTS is a JSON array of the environment's hosts, not a comma-separated string. WODBY_PRIMARY_HOST and WODBY_PRIMARY_URL are the canonical ones for links generated outside a request.
  • WODBY_APP_SERVICE_NAME is this service's host name inside the environment. Other services reach the application at that name on port 8080.
  • WODBY_ENV_TYPE tells a development environment from a production-like one.
  • Requests arrive through Wodby's gateway, which sets X-Forwarded-For and X-Forwarded-Proto.

In a development workspace

  • The checkout is mounted at /usr/src/app and the container runs the project with dotnet watch. A change is applied to the running application with Hot Reload, or the application is rebuilt and restarted when it can't be applied, in the same container, usually within a few seconds. Nothing has to be restarted or deployed for a code change. A build that fails leaves the running application up; the compiler's errors are in the service's logs.
  • The project is chosen as in the build; WORKSPACE_DOTNET_PROJECT on the service selects another one, such as src/Api/Api.csproj. WORKSPACE_DOTNET_COMMAND replaces the start command.
  • Workspace setup restores dependencies with workspace-dotnet prepare: the solution's when there is exactly one *.sln or *.slnx at the root, otherwise the project's, and the local tools of .config/dotnet-tools.json. With a packages.lock.json, restores fail instead of rewriting it.
  • DOTNET_ENVIRONMENT is Development unless the service sets it, and launchSettings.json is not used. Browser refresh is off: reload the page by hand.
  • NuGet packages are kept in .wodby-workspace/nuget in the checkout. .wodby-workspace/, bin/ and obj/ are kept out of Git status without touching .gitignore.
  • A change to variables or linked services still needs a deployment of the environment.

Check the result

  • curl -s -o /dev/null -w '%{http_code}' localhost:8080 from the container shows whether the application answers on the expected port.
  • dotnet build in the checkout shows compile errors at once; the service's logs show them too when a change does not appear.

ASP.NET Core on Wodby

This service is the .NET service with settings for ASP.NET Core applications. Everything in the .NET service's guidance applies: the build, port 8080, linked-service variables, Data Protection keys and the development workspace.

What this service adds

  • ASPNETCORE_FORWARDEDHEADERS_ENABLED is true. ASP.NET Core then applies the X-Forwarded-For and X-Forwarded-Proto headers that Wodby's gateway sets, so HttpContext.Request.Scheme is https for visitors on HTTPS, generated links and redirects use it, and Connection.RemoteIpAddress is the visitor's address. Do not add UseForwardedHeaders with other settings, and do not add UseHttpsRedirection: TLS ends at the gateway, and checks inside the environment use plain HTTP.
  • The ASP.NET Core boilerplate, which restricts host names to WODBY_HOSTS, the app service's name and localhost, and answers /healthz.

Environment

  • ASPNETCORE_ENVIRONMENT is not set; ASP.NET Core falls back to DOTNET_ENVIRONMENT, which is Development in development environments. Elsewhere the application runs as Production, so appsettings.Production.json applies and the developer exception page is off.
  • Configuration from environment variables uses __ for nesting: a variable on the service named ConnectionStrings__Default is GetConnectionString("Default").

Check the result

  • curl -s -H "Host: $WODBY_APP_SERVICE_NAME" localhost:8080/healthz in the container answers Healthy when the application uses the boilerplate's health check.
  • A 400 Bad Request with an empty body for a domain usually means host filtering does not allow it: compare the domain with WODBY_HOSTS and AllowedHosts.

Обзор

Технический профиль ASP.NET Core

Здесь перечислены версии, которые можно выбрать для ASP.NET Core в стеке или окружении. Сам сервис публикуется ревизиями, и стек ссылается на конкретную ревизию.

Тип сервиса

Сервис приложения

Версии

10.0

Стеки

Стеки, в которые входит ASP.NET Core

ASP.NET Core входит в этот публичный стек. Можно создать приложение из публичного стека как есть или добавить сервис в собственный стек.

CI/CD

Сборка ASP.NET Core из Git-репозитория

Начните с публичного шаблона проекта или подключите собственный репозиторий. В StackMaster CI push в ветку, за которой следит окружение, запускает сборку ASP.NET Core, а пайплайн её развёртывает.

ASP.NET Core boilerplate

Используйте его как есть или клонируйте в свой Git-аккаунт.

wodby/aspnetcore-boilerplate

Git-провайдеры

Репозиторий подключается через интеграцию с его Git-провайдером.

CI-провайдеры

StackMaster CI встроен в платформу: пайплайн описывается в файле .wodby/pipeline.yml в репозитории. Для подключённого репозитория те же шаги может выполнять внешний CI-провайдер с помощью StackMaster CLI.

Реестры контейнеров

Собранные образы по умолчанию попадают в StackMaster Registry или во внешний реестр, подключённый как интеграция.

Переменные окружения из интеграций

Интеграция с переменными один раз сохраняет учётные данные стороннего сервиса. Подключите её к ASP.NET Core, и StackMaster передаст их в контейнер как переменные окружения во время работы, а не при сборке образа.

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

Конфигурация сервиса ASP.NET Core

Сервис ASP.NET Core объявляет следующее. Если значение можно изменить, его задаёт стек, а каждое окружение может его переопределить.

Технические домены

StackMaster выдаёт каждому публичному HTTP-порту технический домен с TLS-сертификатом и продлевает сертификат. Порт, который сервис помечает как частный, домен не получает. Можно добавить собственные домены.

Связи сервиса

Каждая связь — это подключение ASP.NET Core к другому сервису. На какой сервис указывает связь, задаёт стек. На карточках перечислены публичные сервисы, которые подходят для каждой связи.

sendmail

Сервисы, которые подходят для этой связи

redis

Сервисы, которые подходят для этой связи