Skip to content

Configuration ​

Introduction ​

All configuration of a DotBlaze application lives in the config directory. Like Laravel, each file covers one area of the framework: App.cs, Auth.cs, Broadcasting.cs, Cache.cs, Database.cs (including Redis connections), Filesystems.cs, Mail.cs, Queue.cs, Services.cs, and Session.cs in a new application.

The files are ordinary C# classes, compiled into your application. Unlike a JSON file, a config class may contain logic: read environment variables with typed defaults, branch on the environment, or compute a value.

Under the hood, DotBlaze loads these values into ASP.NET Core's IConfiguration, so everything the .NET configuration system offers (environment variables, appsettings.json, user secrets, command line arguments) keeps working.

Configuration Files ​

A configuration file is a class that extends ConfigFile and returns its values from Values(), usually as an anonymous object. Given config/App.cs:

csharp
namespace Blog.Configuration;

public class AppConfig : ConfigFile
{
    public override object Values() => new
    {
        name = "Blog",
        url = Env("APP_URL"),
        key = Env("APP_KEY"),
        locale = "en",
    };
}

the values are available as app.name, app.url, app.key, and app.locale. The first segment, the section, is the class name without the Config suffix, in snake case: AppConfig is app, MyServicesConfig is my_services. Override Section to choose another name:

csharp
public override string Section => "payments";

Nested objects add more segments, so connections = new { sqlite = new { database = "..." } } in DatabaseConfig becomes database.connections.sqlite.database. A few more rules:

  • C# keywords used as keys need an @ prefix, which is not part of the key: @default = "sqlite" is database.default.
  • Keys that are not valid C# names go in a dictionary: supervisors = new Dictionary<string, object> { ["supervisor-1"] = new { ... } }.
  • Arrays add an index: queue = new[] { "high", "default" } becomes queue.queue.0 and queue.queue.1.
  • null values are left out, as if the key did not exist.
  • Keys are case-insensitive.

You may add your own classes. A class PaymentsConfig : ConfigFile anywhere in the application assembly is available under the payments. prefix without any registration; by convention it lives in config/Payments.cs. Two classes with the same section are an error at startup.

Configuration is loaded before the service container is built, so a config class has no dependency injection, and it needs a public parameterless constructor. Packages ship default values through MergeConfig in their provider instead.

NOTE

DotBlaze no longer reads config/*.json. An application that still has such a file fails at startup with a message that points here. To upgrade, replace each file with a class: "key": "value" becomes key = "value", objects become new { ... }, and "${NAME}" becomes Env("NAME").

Environment Configuration ​

It is often helpful to have different values per environment: a local SQLite database during development, PostgreSQL in production, a different password on every server.

Reading Environment Variables ​

Env reads an environment variable inside a config class, like Laravel's env() helper:

csharp
public class DatabaseConfig : ConfigFile
{
    public override object Values() => new
    {
        @default = Env("DB_CONNECTION", "sqlite"),
        connections = new
        {
            pgsql = new
            {
                driver = "pgsql",
                host = Env("DB_HOST", "127.0.0.1"),
                port = Env("DB_PORT", 5432),
                password = Env("DB_PASSWORD"),
            },
        },
    };
}
  • Env("NAME") returns the value, or null when the variable is missing or empty (so the key is left out).
  • Env("NAME", fallback) returns the fallback instead, and converts the value to the fallback's type. Booleans accept true/false, 1/0, yes/no, and on/off. A value that cannot be converted stops the application with an error naming the variable.

Environment Specific Values ​

Because a config class is code, it may branch on the environment. IsDevelopment, IsProduction, IsEnvironment("Staging", "Testing"), and EnvironmentName describe the current environment, and BasePath("...") gives a path inside the application root:

csharp
public class AppConfig : ConfigFile
{
    public override object Values() => new
    {
        name = "Blog",
        debug = Env("APP_DEBUG", IsDevelopment),
        keys_path = IsProduction ? "/var/lib/blog/keys" : BasePath("storage/framework/keys"),
    };
}

The .env File ​

Before running the config classes, DotBlaze reads the .env file in the application root and adds its entries to the process environment, like Laravel's .env, so Env sees them:

ini
# Lines starting with # are comments.
DB_PASSWORD="secret"
AWS_ACCESS_KEY_ID=...
AWS_SECRET_ACCESS_KEY=...
AWS_BUCKET=blog-uploads

A few rules worth knowing:

  • Values may be wrapped in single or double quotes; the quotes are removed.
  • .env never overwrites a variable that already exists in the environment. A real environment variable always wins.
  • The config classes run once, at startup. Changing .env requires a restart.

Your .env file should not be committed to source control, since each developer and server may need a different environment. The template's .gitignore already excludes it; commit a .env.example with the variable names (and safe defaults) instead.

Overriding Values With Environment Variables ​

Every config key can also be set directly with an environment variable, using __ (two underscores) in place of each dot. This is standard ASP.NET Core behaviour and needs no Env call in the config class:

shell
# Overrides name in config/App.cs
export app__name="Blog (staging)"

# Overrides the PostgreSQL host in config/Database.cs
export database__connections__pgsql__host=db.internal

The CI workflow configures its test databases this way.

When the application is started as a web server, command line arguments work too: dotblaze serve -- --app:name=Demo. Arguments passed to a console command are not added to the configuration.

Configuration Priority ​

The config/*.cs classes have the lowest priority. From lowest to highest:

  1. Defaults from packages (MergeConfig).
  2. config/*.cs.
  3. appsettings.json and appsettings.{Environment}.json, if you add them. The template does not create these files.
  4. User secrets (Development only).
  5. Environment variables, such as app__name.
  6. Command line arguments (web server only).

Determining the Current Environment ​

Set APP_ENV in .env, like Laravel. DotBlaze loads it before creating the ASP.NET Core host, so it controls environment-specific appsettings, development services, error pages, and IsDevelopment() / IsProduction():

dotenv
# Local development
APP_ENV=local
# On the production server, use instead:
# APP_ENV=production

local and development map to Development; production, staging, and testing map to Production, Staging, and Testing (case-insensitive). Other names, such as Preview, are preserved. The template and sample .env.example use local.

Read the effective environment with Config.Get<string>("app.env"). This is the normalized host environment (Development for APP_ENV=local), not the raw .env text. The app config exposes it as env = EnvironmentName; DotBlaze keeps app.env synchronized with the host, including test-host overrides. Do not use app__env, appsettings.json, or runtime Config.Set to select the host environment: configuration classes load after the host has selected its environment.

A real process variable APP_ENV overrides .env. A nonempty APP_ENV takes precedence over the normal .NET environment selection; if it is missing or empty, ASP.NET Core's existing DOTNET_ENVIRONMENT / ASPNETCORE_ENVIRONMENT / command-line behavior remains the fallback, defaulting to Production. Explicit test-host environment overrides still apply. Existing deployments with APP_ENV=local must set APP_ENV=production rather than relying on DOTNET_ENVIRONMENT=Production.

Restart the application after changing .env; the host environment cannot change while running. This works with dotblaze serve, dotblaze serve --watch, dotnet run, and console commands.

In Development and Testing, DotBlaze shows its detailed developer exception page in the browser. The debug option in config/App.cs overrides the environment default (see Error Handling). You may check the environment in a provider through app.Environment.IsDevelopment().

Accessing Configuration Values ​

Use the Config facade anywhere in your application. Like Laravel's config() helper, it uses dot notation: the file name followed by the keys inside it.

csharp
var name = Config.Get<string>("app.name");

// With a fallback when the key is missing:
var lifetime = Config.Get("session.lifetime", 120);

Get<T> converts the value to T (configuration values are stored as strings), and returns default(T) when the key is missing. The overload with a fallback infers T from the fallback.

The template's HomeController reads the application name this way:

csharp
public class HomeController : BaseController
{
    public IActionResult Index() => View(model: Config.Get<string>("app.name"));
}

Setting Values at Runtime ​

Config.Set changes a value at runtime:

csharp
Config.Set("queue.default", "sync");

The value is a string (or null). As in Laravel, it applies to the whole running application, not only to the current request, and it is not written back to the config class. Its main use is in tests.

Constructor Injection ​

The Config facade is a thin wrapper around IConfiguration, which you may inject instead. IConfiguration uses : as the separator rather than .:

csharp
public class ReportService(IConfiguration config)
{
    public string Locale => config["app:locale"] ?? "en";
}

Providers receive the configuration directly in Register(IServiceCollection services, IConfiguration config). See Service Providers.

Framework Configuration Keys ​

These are the keys DotBlaze itself reads. The database, queue, and storage pages explain their sections in detail.

KeyDefaultPurpose
app.namethe assembly nameApplication name; used by the welcome page and as the Data Protection application name.
app.keyEnv("APP_KEY")The application key for encryption, cookies, CSRF, and signed URLs. Create one with key:generate. See Encryption.
app.keys_pathstorage/framework/keysWithout app.key: the folder where generated Data Protection keys are stored. See Deployment.
app.localeenThe default locale: translations, the culture of dates and numbers, and validation messages.
auth.login/loginWhere unauthenticated users are redirected.
auth.home/Where authenticated users are redirected by the guest middleware.
session.lifetime120Session and login lifetime in minutes (sliding).
auth.modelthe only IAuthenticatable classFull type name of the user model; needed only when the app has more than one.
hashing.iterations600000PBKDF2 iterations used by Hash.Make. See Hashing.
database.default, database.connections.*See Database.
queue.default, queue.connections.*syncSee Queues.
queue.workerfalseRun a queue worker inside the web application.
queue.worker_queuesdefaultComma-separated queues for the in-app worker.
filesystems.default, filesystems.disks.*See File Storage.
Logging.LogLevel.*Standard ASP.NET Core log levels. See Logging.
app.timezoneUTCThe time zone scheduled tasks are evaluated in.
app.faker_localeenThe language of factory fake data.
app.fallback_locale, app.lang_pathSee Localization.
session.driver, session.connection, session.table, session.prefix, session.cookieSee Session.
auth.tokens.expiration(none)Minutes after which API tokens expire.
services.*Credentials of external services, e.g. social login providers (config/Services.cs).
app.maintenance.driver, app.maintenance.storefileWhere the maintenance mode state lives, see below.

Maintenance Mode ​

While you deploy or migrate, dotblaze down answers every request with 503 Service Unavailable (a simple page, or { "message": "Service Unavailable" } for JSON requests), and dotblaze up brings the application back:

shell
dotblaze down
dotblaze up
Option
--retry=60Send Retry-After: 60.
--refresh=15Make browsers reload the page every 15 seconds.
--secret=xyz / --with-secretVisiting /xyz (or the generated path the command prints) sets a cookie that lets that browser use the site normally for 12 hours, to check a deployment.
--redirect=/statusRedirect every request there instead.
--render=errors/503Render this Razor view instead of the built-in page; its model is the MaintenanceOptions.
--status=503Another status code.

Static files keep working, so a custom page can load its CSS. Keep paths such as health checks or webhooks working in a provider's Boot method:

csharp
Maintenance.Except("/health", "/webhooks/*");

The state is the file storage/framework/down, so it applies to one server. With several servers, keep it in a shared cache instead, in config/App.cs:

csharp
maintenance = new { driver = "cache", store = "redis" },

Maintenance.Down(...), Maintenance.Up(), and Maintenance.Active() do the same from code.

Complete Example: A Configured Endpoint ​

In the Blog template application, create a new, uniquely named config section and a controller:

csharp
// config/Reading.cs
using DotBlaze;

namespace Blog.Configuration;

public class ReadingConfig : ConfigFile
{
    public override object Values() => new
    {
        heading = Env("READING_HEADING", "Recommended reading"),
        page_size = Env("READING_PAGE_SIZE", 10),
    };
}
csharp
// app/Http/Controllers/ReadingController.cs
using DotBlaze;
using Microsoft.AspNetCore.Mvc;

namespace Blog.Controllers;

public class ReadingController : BaseController
{
    public IActionResult Index() => Json(new
    {
        heading = Config.Get("reading.heading", "Recommended reading"),
        pageSize = Config.Get("reading.page_size", 10),
    });
}

Inside routes/web.cs's existing Web.Map(), add:

csharp
Route.Get<Blog.Controllers.ReadingController>("/reading", c => c.Index)
    .Name("reading.index");

Add READING_PAGE_SIZE=5 to .env, restart with dotblaze serve, and open /reading. Expected JSON: {"heading":"Recommended reading","pageSize":5}. A direct reading__page_size=7 environment variable wins over the config class and produces 7. An invalid READING_PAGE_SIZE=abc fails startup instead of silently choosing a page size.