Delen via


ASP.NET Core Blazor-configuratie

Notitie

Dit is niet de nieuwste versie van dit artikel. Zie de .NET 9-versie van dit artikelvoor de huidige release.

Waarschuwing

Deze versie van ASP.NET Core wordt niet meer ondersteund. Zie de .NET- en .NET Core-ondersteuningsbeleidvoor meer informatie. Zie de .NET 9-versie van dit artikelvoor de huidige release.

Belangrijk

Deze informatie heeft betrekking op een pre-releaseproduct dat aanzienlijk kan worden gewijzigd voordat het commercieel wordt uitgebracht. Microsoft geeft geen garanties, uitdrukkelijk of impliciet, met betrekking tot de informatie die hier wordt verstrekt.

Zie de .NET 9-versie van dit artikelvoor de huidige release.

In dit artikel wordt uitgelegd hoe u Blazor apps configureert, waaronder app-instellingen, verificatie en logboekregistratieconfiguratie.

Deze richtlijnen zijn van toepassing op projectconfiguratie aan de clientzijde in een Blazor Web App of een zelfstandige Blazor WebAssembly-app.

Standaardgedrag in Blazor Web Apps:

  • Voor configuratie aan de serverzijde:
    • Zie Configuration in ASP.NET Core voor hulp.
    • Alleen configuratie in de hoofd-app-instellingenbestanden van het project wordt geladen.
    • De rest van dit artikel is alleen van toepassing op de configuratie aan de clientzijde in het .Client-project.
  • Voor configuratie aan de clientzijde (.Client project) wordt de configuratie geladen vanuit de volgende app-instellingenbestanden:
    • wwwroot/appsettings.json.
    • wwwroot/appsettings.{ENVIRONMENT}.json, waarbij {ENVIRONMENT} de tijdelijke aanduiding is voor de runtime-omgeving van de app.

In zelfstandige Blazor WebAssembly-apps wordt de configuratie geladen vanuit de volgende app-instellingenbestanden:

  • wwwroot/appsettings.json.
  • wwwroot/appsettings.{ENVIRONMENT}.json, waarbij de placeholder {ENVIRONMENT} de runtime-omgeving van de app is.

Deze richtlijnen zijn van toepassing op het Client project van een gehoste Blazor WebAssembly-oplossing of een Blazor WebAssembly-app.

Zie Configuration in ASP.NET Corevoor server-side ASP.NET Core-appconfiguratie in het Server-project van een gehoste Blazor WebAssembly-oplossing.

Op de client wordt de configuratie geladen vanuit de volgende app-instellingenbestanden:

  • wwwroot/appsettings.json.
  • wwwroot/appsettings.{ENVIRONMENT}.json, waarbij de {ENVIRONMENT} tijdelijke aanduiding de runtime-omgeving van de app is.

Notitie

De logboekregistratieconfiguratie in een app-instellingenbestand wordt standaard niet geladen in wwwroot. Zie de sectie Logboekregistratie verderop in dit artikel voor meer informatie.

In sommige scenario's, zoals met Azure-services, is het belangrijk om een segment met de bestandsnaam van de omgeving te gebruiken dat exact overeenkomt met de naam van de omgeving. Gebruik bijvoorbeeld de bestandsnaam appsettings.Staging.json met een hoofdletter "S" voor de Staging-omgeving. Zie de openings opmerkingen van ASP.NET Core Blazor omgevingenvoor aanbevolen conventies.

Andere configuratieproviders die door de app zijn geregistreerd, kunnen ook configuratie bieden, maar niet alle providers of providerfuncties zijn geschikt:

  • Azure Key Vault-configuratieprovider: de provider wordt niet ondersteund voor beheerde identity en toepassings-id (client-id) met scenario's met clientgeheimen. Toepassings-id met een clientgeheim wordt niet aanbevolen voor een ASP.NET Core-app, met name apps aan de clientzijde, omdat het clientgeheim niet kan worden beveiligd voor toegang tot de Azure Key Vault-service.
  • Azure App-configuratieprovider: de provider is niet geschikt voor een app aan de clientzijde, omdat de app niet wordt uitgevoerd op een server in Azure.

Zie Configuration in ASP.NET Corevoor meer informatie over configuratieproviders.

Waarschuwing

Configuratie- en instellingenbestanden in de webhoofdmap (wwwroot map) zijn zichtbaar voor gebruikers op de client en gebruikers kunnen knoeien met de gegevens. geen app-geheimen, referenties of andere gevoelige gegevens opslaan in een webhoofdbestand.

Configuratie van app-instellingen

Configuratie in app-instellingen wordt standaard geladen. In het volgende voorbeeld wordt een ui-configuratiewaarde opgeslagen in een app-instellingenbestand en automatisch geladen door het Blazor framework. De waarde wordt gelezen door een onderdeel.

wwwroot/appsettings.json:

{
    "h1FontSize": "50px"
}

Injecteer een IConfiguration exemplaar in een onderdeel om toegang te krijgen tot de configuratiegegevens.

ConfigExample.razor:

@page "/config-example"
@inject IConfiguration Configuration

<PageTitle>Configuration</PageTitle>

<h1 style="font-size:@Configuration["h1FontSize"]">
    Configuration example (50px)
</h1>
@page "/config-example"
@inject IConfiguration Configuration

<PageTitle>Configuration</PageTitle>

<h1 style="font-size:@Configuration["h1FontSize"]">
    Configuration example (50px)
</h1>
@page "/config-example"
@inject IConfiguration Configuration

<h1 style="font-size:@Configuration["h1FontSize"]">
    Configuration example
</h1>
@page "/config-example"
@inject IConfiguration Configuration

<h1 style="font-size:@Configuration["h1FontSize"]">
    Configuration example
</h1>
@page "/config-example"
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

<h1 style="font-size:@Configuration["h1FontSize"]">
    Configuration example
</h1>
@page "/config-example"
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

<h1 style="font-size:@Configuration["h1FontSize"]">
    Configuration example
</h1>

Clientbeveiligingsbeperkingen voorkomen directe toegang tot bestanden via gebruikerscode, inclusief instellingenbestanden voor app-configuratie. Als u configuratiebestanden wilt lezen naast appsettings.json/appsettings.{ENVIRONMENT}.json uit de map wwwroot in de configuratie, gebruikt u een HttpClient.

Waarschuwing

Configuratie- en instellingenbestanden in de webhoofdmap (wwwroot map) zijn zichtbaar voor gebruikers op de client en gebruikers kunnen knoeien met de gegevens. geen app-geheimen, referenties of andere gevoelige gegevens opslaan in een webhoofdbestand.

In het volgende voorbeeld wordt een configuratiebestand (cars.json) gelezen in de configuratie van de app.

wwwroot/cars.json:

{
    "size": "tiny"
}

Voeg de naamruimte voor Microsoft.Extensions.Configuration toe aan het Program-bestand:

using Microsoft.Extensions.Configuration;

Wijzig de bestaande HttpClient-serviceregistratie om de client te gebruiken om het bestand te lezen:

var http = new HttpClient()
{
    BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
};

builder.Services.AddScoped(sp => http);

using var response = await http.GetAsync("cars.json");
using var stream = await response.Content.ReadAsStreamAsync();

builder.Configuration.AddJsonStream(stream);

In het voorgaande voorbeeld wordt het basisadres ingesteld met builder.HostEnvironment.BaseAddress (IWebAssemblyHostEnvironment.BaseAddress), waarmee het basisadres voor de app wordt opgehaald en doorgaans wordt afgeleid van de href waarde van de <base> tag op de hostpagina.

Geheugenconfiguratiebron

In het volgende voorbeeld wordt een MemoryConfigurationSource in het Program-bestand gebruikt om extra configuraties op te geven.

Voeg de naamruimte voor Microsoft.Extensions.Configuration.Memory toe aan het Program-bestand:

using Microsoft.Extensions.Configuration.Memory;

In het bestand Program:

var vehicleData = new Dictionary<string, string?>()
{
    { "color", "blue" },
    { "type", "car" },
    { "wheels:count", "3" },
    { "wheels:brand", "Blazin" },
    { "wheels:brand:type", "rally" },
    { "wheels:year", "2008" },
};

var memoryConfig = new MemoryConfigurationSource { InitialData = vehicleData };

builder.Configuration.Add(memoryConfig);

Injecteer een IConfiguration exemplaar in een onderdeel om toegang te krijgen tot de configuratiegegevens.

MemoryConfig.razor:

@page "/memory-config"
@inject IConfiguration Configuration

<PageTitle>Memory Configuration</PageTitle>

<h1>Memory Configuration Example</h1>

<h2>General specifications</h2>

<ul>
    <li>Color: @Configuration["color"]</li>
    <li>Type: @Configuration["type"]</li>
</ul>

<h2>Wheels</h2>

<ul>
    <li>Count: @Configuration["wheels:count"]</li>
    <li>Brand: @Configuration["wheels:brand"]</li>
    <li>Type: @Configuration["wheels:brand:type"]</li>
    <li>Year: @Configuration["wheels:year"]</li>
</ul>
@page "/memory-config"
@inject IConfiguration Configuration

<PageTitle>Memory Configuration</PageTitle>

<h1>Memory Configuration Example</h1>

<h2>General specifications</h2>

<ul>
    <li>Color: @Configuration["color"]</li>
    <li>Type: @Configuration["type"]</li>
</ul>

<h2>Wheels</h2>

<ul>
    <li>Count: @Configuration["wheels:count"]</li>
    <li>Brand: @Configuration["wheels:brand"]</li>
    <li>Type: @Configuration["wheels:brand:type"]</li>
    <li>Year: @Configuration["wheels:year"]</li>
</ul>
@page "/memory-config"
@inject IConfiguration Configuration

<h1>Memory configuration example</h1>

<h2>General specifications</h2>

<ul>
    <li>Color: @Configuration["color"]</li>
    <li>Type: @Configuration["type"]</li>
</ul>

<h2>Wheels</h2>

<ul>
    <li>Count: @Configuration["wheels:count"]</li>
    <li>Brand: @Configuration["wheels:brand"]</li>
    <li>Type: @Configuration["wheels:brand:type"]</li>
    <li>Year: @Configuration["wheels:year"]</li>
</ul>
@page "/memory-config"
@inject IConfiguration Configuration

<h1>Memory configuration example</h1>

<h2>General specifications</h2>

<ul>
    <li>Color: @Configuration["color"]</li>
    <li>Type: @Configuration["type"]</li>
</ul>

<h2>Wheels</h2>

<ul>
    <li>Count: @Configuration["wheels:count"]</li>
    <li>Brand: @Configuration["wheels:brand"]</li>
    <li>Type: @Configuration["wheels:brand:type"]</li>
    <li>Year: @Configuration["wheels:year"]</li>
</ul>
@page "/memory-config"
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

<h1>Memory configuration example</h1>

<h2>General specifications</h2>

<ul>
    <li>Color: @Configuration["color"]</li>
    <li>Type: @Configuration["type"]</li>
</ul>

<h2>Wheels</h2>

<ul>
    <li>Count: @Configuration["wheels:count"]</li>
    <li>Brand: @Configuration["wheels:brand"]</li>
    <li>Type: @Configuration["wheels:brand:type"]</li>
    <li>Year: @Configuration["wheels:year"]</li>
</ul>
@page "/memory-config"
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

<h1>Memory configuration example</h1>

<h2>General specifications</h2>

<ul>
    <li>Color: @Configuration["color"]</li>
    <li>Type: @Configuration["type"]</li>
</ul>

<h2>Wheels</h2>

<ul>
    <li>Count: @Configuration["wheels:count"]</li>
    <li>Brand: @Configuration["wheels:brand"]</li>
    <li>Type: @Configuration["wheels:brand:type"]</li>
    <li>Year: @Configuration["wheels:year"]</li>
</ul>

Haal een sectie van de configuratie in C#-code op met IConfiguration.GetSection. In het volgende voorbeeld wordt de sectie wheels voor de configuratie in het voorgaande voorbeeld verkregen:

@code {
    protected override void OnInitialized()
    {
        var wheelsSection = Configuration.GetSection("wheels");

        ...
    }
}

Verificatieconfiguratie

Geef openbare-verificatieconfiguratie op in een app-instellingenbestand.

wwwroot/appsettings.json:

{
  "Local": {
    "Authority": "{AUTHORITY}",
    "ClientId": "{CLIENT ID}"
  }
}

Laad de configuratie voor een Identity provider met ConfigurationBinder.Bind in het Program-bestand. In het volgende voorbeeld wordt de configuratie voor een OIDC-providergeladen:

builder.Services.AddOidcAuthentication(options =>
    builder.Configuration.Bind("Local", options.ProviderOptions));

Waarschuwing

Configuratie- en instellingenbestanden in de webhoofdmap (wwwroot map) zijn zichtbaar voor gebruikers op de client en gebruikers kunnen knoeien met de gegevens. geen app-geheimen, referenties of andere gevoelige gegevens opslaan in een webhoofdbestand.

Configuratie van logboekregistratie

Deze sectie is van toepassing op apps die logboekregistratie configureren via een app-instellingenbestand in de map wwwroot.

Voeg het Microsoft.Extensions.Logging.Configuration-pakket toe aan de app.

Notitie

Raadpleeg de artikelen onder Pakketten installeren en beheren bij Package consumption workflow (NuGet-documentatie)voor hulp bij het toevoegen van pakketten aan .NET-apps. Bevestig de juiste pakketversies op NuGet.org.

Geef in het bestand met app-instellingen de configuratie van logboekregistratie op. De configuratie voor het logboek wordt geladen in het bestand Program.

wwwroot/appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  }
}

In het bestand Program:

builder.Logging.AddConfiguration(
    builder.Configuration.GetSection("Logging"));

Configuratie van hostbouwer

Lees de configuratie van hostbouwer uit WebAssemblyHostBuilder.Configuration in het Program-bestand:

var hostname = builder.Configuration["HostName"];

Configuratie met cache

Configuratiebestanden worden in de cache opgeslagen voor offlinegebruik. Met Progressive Web Applications (PWA's)kunt u alleen configuratiebestanden bijwerken bij het maken van een nieuwe implementatie. Het bewerken van configuratiebestanden tussen implementaties heeft geen effect omdat:

  • Gebruikers hebben versies in de cache opgeslagen van de bestanden die ze blijven gebruiken.
  • De service-worker.js- en service-worker-assets.js-bestanden van de PWA moeten opnieuw worden opgebouwd op compilatie, wat aangeeft dat de app bij het volgende onlinebezoek van de gebruiker opnieuw is geïmplementeerd.

Zie ASP.NET Core Blazor Progressive Web Application (PWA)voor meer informatie over hoe achtergrondupdates worden verwerkt door PWA's.

Configuratie van opties

Opties-configuratie vereist het toevoegen van een pakketreferentie voor het Microsoft.Extensions.Options.ConfigurationExtensions NuGet-pakket.

Notitie

Zie de artikelen onder Pakketten installeren en beheren in Package consumption workflow (NuGet-documentatie)voor richtlijnen over het toevoegen van pakketten aan .NET-apps. Bevestig de juiste pakketversies op NuGet.org.

Voorbeeld:

OptionsExample.cs:

public class OptionsExample
{
    public string? Option1 { get; set; }
    public string? Option2 { get; set; }
}

In appsettings.json:

"OptionsExample": {
  "Option1": "Option1 Value",
  "Option2": "Option2 Value"
}
builder.Services.Configure<OptionsExample>(
    builder.Configuration.GetSection("OptionsExample"));

Het volgende Razor onderdeel haalt de instellingen op met de @inject instructie of het [Inject] kenmerk.

Options.razor:

@page "/options"
@using Microsoft.Extensions.Options
@inject IOptions<OptionsExample>? OptionsExample1

<h1>Options</h1>

<h2>
    &commat;inject approach
</h2>

<ul>
    <li>@OptionsExample1?.Value.Option1</li>
    <li>@OptionsExample1?.Value.Option2</li>
</ul>

<h2>
    [Inject] approach
</h2>

<ul>
    <li>@OptionsExample2?.Value.Option1</li>
    <li>@OptionsExample2?.Value.Option2</li>
</ul>

@code {
    [Inject]
    public IOptions<OptionsExample>? OptionsExample2 { get; set; }
}

Niet alle functies van ASP.NET Kernopties worden ondersteund in Razor onderdelen. De configuratie van IOptionsSnapshot<TOptions> en IOptionsMonitor<TOptions> wordt bijvoorbeeld ondersteund, maar het opnieuw compileren van optiewaarden voor deze interfaces wordt niet ondersteund buiten het opnieuw laden van de app door de app aan te vragen op een nieuw browsertabblad of door de knop voor opnieuw laden van de browser te selecteren. Als u alleen StateHasChanged aanroept, worden momentopname- of bewaakte optiewaarden niet bijgewerkt wanneer de onderliggende configuratie wordt gewijzigd.