diff --git a/aspnetcore/blazor/call-web-api.md b/aspnetcore/blazor/call-web-api.md index db0a7cdb3763..8a7f88cd05b4 100644 --- a/aspnetcore/blazor/call-web-api.md +++ b/aspnetcore/blazor/call-web-api.md @@ -45,7 +45,7 @@ Reference the [`System.Net.Http.Json`](https://www.nuget.org/packages/System.Net ## Add the `HttpClient` service -In `Program.Main`, add an service if it isn't already present from a Blazor project template used to create the app: +In `Program.cs`, add an service if it isn't already present from a Blazor project template used to create the app: ```csharp builder.Services.AddScoped(sp => @@ -210,7 +210,7 @@ Reference the [`Microsoft.Extensions.Http`](https://www.nuget.org/packages/Micro In the preceding example, the `{VERSION}` placeholder is the version of the package. -In `Program.Main` of the `Program.cs` file: +In `Program.cs`: ```csharp builder.Services.AddHttpClient("WebAPI", client => @@ -303,7 +303,7 @@ public class WeatherForecastHttpClient } ``` -In `Program.Main` of the `Program.cs` file: +In `Program.cs`: ```csharp builder.Services.AddHttpClient(client => @@ -389,7 +389,7 @@ For more information on Fetch API options, see [MDN web docs: WindowOrWorkerGlob The following example calls a web API. The example requires a running web API based on the sample app described by the article. This example makes requests to the web API at `https://localhost:10000/api/TodoItems`. If a different web API address is used, update the `ServiceEndpoint` constant value in the component's `@code` block. -The following example makes a [cross-origin resource sharing (CORS)](xref:security/cors) request from `http://localhost:5000` or `https://localhost:5001` to the web API. Add the following CORS middleware configuration to the web API's service's `Startup.Configure` method: +The following example makes a [cross-origin resource sharing (CORS)](xref:security/cors) request from `http://localhost:5000` or `https://localhost:5001` to the web API. Add the following CORS middleware configuration to the web API's service's `Program.cs` file: ```csharp app.UseCors(policy => @@ -484,10 +484,10 @@ For more information, see . A Blazor Server app doesn't include an service by default. Provide an to the app using the [`HttpClient` factory infrastructure](xref:fundamentals/http-requests). -In `Startup.`ConfigureServices` of `Startup.cs`: +In `Program.cs`: ```csharp -services.AddHttpClient(); +builder.Services.AddHttpClient(); ``` The following Blazor Server Razor component makes a request to a web API for GitHub branches similar to the *Basic Usage* example in the article. @@ -641,7 +641,7 @@ Reference the [`System.Net.Http.Json`](https://www.nuget.org/packages/System.Net ## Add the `HttpClient` service -In `Program.Main`, add an service if it isn't already present from a Blazor project template used to create the app: +In `Program.cs`, add an service if it isn't already present from a Blazor project template used to create the app: ```csharp builder.Services.AddScoped(sp => @@ -806,7 +806,7 @@ Reference the [`Microsoft.Extensions.Http`](https://www.nuget.org/packages/Micro In the preceding example, the `{VERSION}` placeholder is the version of the package. -In `Program.Main` of the `Program.cs` file: +In `Program.cs`: ```csharp builder.Services.AddHttpClient("WebAPI", client => @@ -899,7 +899,7 @@ public class WeatherForecastHttpClient } ``` -In `Program.Main` of the `Program.cs` file: +In `Program.cs`: ```csharp builder.Services.AddHttpClient(client => @@ -1239,7 +1239,7 @@ Reference the [`System.Net.Http.Json`](https://www.nuget.org/packages/System.Net ## Add the `HttpClient` service -In `Program.Main`, add an service if it isn't already present from a Blazor project template used to create the app: +In `Program.cs`, add an service if it isn't already present from a Blazor project template used to create the app: ```csharp builder.Services.AddScoped(sp => @@ -1404,7 +1404,7 @@ Reference the [`Microsoft.Extensions.Http`](https://www.nuget.org/packages/Micro In the preceding example, the `{VERSION}` placeholder is the version of the package. -In `Program.Main` of the `Program.cs` file: +In `Program.cs`: ```csharp builder.Services.AddHttpClient("WebAPI", client => @@ -1497,7 +1497,7 @@ public class WeatherForecastHttpClient } ``` -In `Program.Main` of the `Program.cs` file: +In `Program.cs`: ```csharp builder.Services.AddHttpClient(client => diff --git a/aspnetcore/blazor/components/control-head-content.md b/aspnetcore/blazor/components/control-head-content.md index e24956437f3a..4a563f9e6c20 100644 --- a/aspnetcore/blazor/components/control-head-content.md +++ b/aspnetcore/blazor/components/control-head-content.md @@ -48,7 +48,7 @@ Specify the page's title with the `PageTitle` component. Specify `` elemen The `HeadOutlet` component renders content provided by `HeadContent` components. -In an app created from the Blazor WebAssembly project template, the `HeadOutlet` component is added to the collection of the in `Program.Main`: +In an app created from the Blazor WebAssembly project template, the `HeadOutlet` component is added to the collection of the in `Program.cs`: ```csharp builder.RootComponents.Add("head::after"); diff --git a/aspnetcore/blazor/components/index.md b/aspnetcore/blazor/components/index.md index efc630cc67f5..a01742bcb3b7 100644 --- a/aspnetcore/blazor/components/index.md +++ b/aspnetcore/blazor/components/index.md @@ -665,18 +665,18 @@ In the event a component must be updated based on an external event, such as a t Register the services: -* In a Blazor WebAssembly app, register the services as singletons in `Program.Main`: +* In a Blazor WebAssembly app, register the services as singletons in `Program.cs`: ```csharp builder.Services.AddSingleton(); builder.Services.AddSingleton(); ``` -* In a Blazor Server app, register the services as scoped in `Startup.ConfigureServices`: +* In a Blazor Server app, register the services as scoped in `Program.cs`: ```csharp - services.AddScoped(); - services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); ``` Use the `NotifierService` to update a component. @@ -1057,7 +1057,7 @@ await Blazor.rootComponents.add(containerElement, 'counter', { incrementAmount: ## Blazor custom elements -Experimental support is available for building custom elements using the the [`Microsoft.AspNetCore.Components.CustomElements` NuGet package](https://www.nuget.org/packages/microsoft.aspnetcore.components.customelements). Custom elements use standard HTML interfaces to implement custom HTML elements. +Experimental support is available for building custom elements using the [`Microsoft.AspNetCore.Components.CustomElements` NuGet package](https://www.nuget.org/packages/microsoft.aspnetcore.components.customelements). Custom elements use standard HTML interfaces to implement custom HTML elements. Register a root component as a custom element: @@ -1741,7 +1741,7 @@ In the event a component must be updated based on an external event, such as a t Register the services: -* In a Blazor WebAssembly app, register the services as singletons in `Program.Main`: +* In a Blazor WebAssembly app, register the services as singletons in `Program.cs`: ```csharp builder.Services.AddSingleton(); @@ -2686,7 +2686,7 @@ In the event a component must be updated based on an external event, such as a t Register the services: -* In a Blazor WebAssembly app, register the services as singletons in `Program.Main`: +* In a Blazor WebAssembly app, register the services as singletons in `Program.cs`: ```csharp builder.Services.AddSingleton(); diff --git a/aspnetcore/blazor/components/prerendering-and-integration.md b/aspnetcore/blazor/components/prerendering-and-integration.md index a06b5429e61d..aebacd058c78 100644 --- a/aspnetcore/blazor/components/prerendering-and-integration.md +++ b/aspnetcore/blazor/components/prerendering-and-integration.md @@ -732,7 +732,7 @@ For more information, see . ## Preserve prerendered state -Without preserving prerendered state, any state that used during prerendering is lost and must be recreated when the app is fully loaded. If any state is setup asynchronously, the UI may flicker as the the prerendered UI is replaced with temporary placeholders and then fully rendered again. +Without preserving prerendered state, any state that used during prerendering is lost and must be recreated when the app is fully loaded. If any state is setup asynchronously, the UI may flicker as the prerendered UI is replaced with temporary placeholders and then fully rendered again. To solve these problems, Blazor supports persisting state in a prerendered page using the [Preserve Component State Tag Helper](xref:mvc/views/tag-helpers/builtin-th/preserve-component-state-tag-helper) (``). Add the `` tag inside the closing `` tag of `_Layout.cshtml`. @@ -866,7 +866,7 @@ To set up prerendering for a hosted Blazor WebAssembly app: 1. **Delete** the `wwwroot/index.html` file from the Blazor WebAssembly **`Client`** project. -1. In the **`Client`** project, **delete** the following line in `Program.Main` (`Program.cs`): +1. In the **`Client`** project, **delete** the following line in `Program.cs`: ```diff - builder.RootComponents.Add("#app"); @@ -1052,7 +1052,7 @@ Additional work might be required depending on the static resources that compone ## Render components in a page or view with a CSS selector -After [configuring the solution](#solution-configuration), including the [additional configuration](#configuration-for-embedding-razor-components-into-pages-and-views), add root components to the **`Client`** project of a hosted Blazor WebAssembly solution in `Program.Main`. In the following example, the `Counter` component is declared as a root component with a CSS selector that selects the element with the `id` that matches `counter-component`. In the following example, the **`Client`** project's namespace is `BlazorHosted.Client`. +After [configuring the solution](#solution-configuration), including the [additional configuration](#configuration-for-embedding-razor-components-into-pages-and-views), add root components to the **`Client`** project of a hosted Blazor WebAssembly solution in `Program.cs`. In the following example, the `Counter` component is declared as a root component with a CSS selector that selects the element with the `id` that matches `counter-component`. In the following example, the **`Client`** project's namespace is `BlazorHosted.Client`. In `Program.cs` of the **`Client`** project, add the namespace for the project's Razor components to the top of the file: @@ -1060,7 +1060,7 @@ In `Program.cs` of the **`Client`** project, add the namespace for the project's + using BlazorHosted.Client.Pages; ``` -After the `builder` is established in `Program.Main`, add the `Counter` component as a root component: +After the `builder` is established in `Program.cs`, add the `Counter` component as a root component: ```diff + builder.RootComponents.Add("#counter-component"); diff --git a/aspnetcore/blazor/debug.md b/aspnetcore/blazor/debug.md index 25e685eed297..46cdc101ea83 100644 --- a/aspnetcore/blazor/debug.md +++ b/aspnetcore/blazor/debug.md @@ -31,7 +31,7 @@ Available scenarios include: For now, you *can't*: * Break on unhandled exceptions. -* Hit breakpoints during app startup before the debug proxy is running. This includes breakpoints in `Program.Main` (`Program.cs`) and breakpoints in the [`OnInitialized{Async}` lifecycle methods](xref:blazor/components/lifecycle#component-initialization-oninitializedasync) of components that are loaded by the first page requested from the app. +* Hit breakpoints during app startup before the debug proxy is running. This includes breakpoints in `Program.cs` and breakpoints in the [`OnInitialized{Async}` lifecycle methods](xref:blazor/components/lifecycle#component-initialization-oninitializedasync) of components that are loaded by the first page requested from the app. * Debug in non-local scenarios (for example, [Windows Subsystem for Linux (WSL)](/windows/wsl/) or [Visual Studio Codespaces](/visualstudio/devinit/devinit-and-codespaces)). * Automatically rebuild the backend **`Server`** app of a hosted Blazor WebAssembly solution during debugging, for example by running the app with [`dotnet watch run`](xref:tutorials/dotnet-watch). @@ -102,7 +102,7 @@ While debugging a Blazor WebAssembly app, you can also debug server code: 1. Press F5 again to let execution continue and see the weather forecast table rendered in the browser. > [!NOTE] -> Breakpoints are **not** hit during app startup before the debug proxy is running. This includes breakpoints in `Program.Main` (`Program.cs`) and breakpoints in the [`OnInitialized{Async}` lifecycle methods](xref:blazor/components/lifecycle#component-initialization-oninitializedasync) of components that are loaded by the first page requested from the app. +> Breakpoints are **not** hit during app startup before the debug proxy is running. This includes breakpoints in `Program.cs` and breakpoints in the [`OnInitialized{Async}` lifecycle methods](xref:blazor/components/lifecycle#component-initialization-oninitializedasync) of components that are loaded by the first page requested from the app. If the app is hosted at a different [app base path](xref:blazor/host-and-deploy/index#app-base-path) than `/`, update the following properties in `Properties/launchSettings.json` to reflect the app's base path: @@ -183,7 +183,7 @@ For information on configuring VS Code assets in the `.vscode` folder, see the * 1. In the browser, navigate to `Counter` page and select the **Click me** button to hit the breakpoint. > [!NOTE] -> Breakpoints are **not** hit during app startup before the debug proxy is running. This includes breakpoints in `Program.Main` (`Program.cs`) and breakpoints in the [`OnInitialized{Async}` lifecycle methods](xref:blazor/components/lifecycle#component-initialization-oninitializedasync) of components that are loaded by the first page requested from the app. +> Breakpoints are **not** hit during app startup before the debug proxy is running. This includes breakpoints in `Program.cs` and breakpoints in the [`OnInitialized{Async}` lifecycle methods](xref:blazor/components/lifecycle#component-initialization-oninitializedasync) of components that are loaded by the first page requested from the app. ## Debug hosted Blazor WebAssembly @@ -276,7 +276,7 @@ While debugging a Blazor WebAssembly app, you can also debug server code: 1. Press + again to let execution continue and see the weather forecast table rendered in the browser. > [!NOTE] -> Breakpoints are **not** hit during app startup before the debug proxy is running. This includes breakpoints in `Program.Main` (`Program.cs`) and breakpoints in the [`OnInitialized{Async}` lifecycle methods](xref:blazor/components/lifecycle#component-initialization-oninitializedasync) of components that are loaded by the first page requested from the app. +> Breakpoints are **not** hit during app startup before the debug proxy is running. This includes breakpoints in `Program.cs` and breakpoints in the [`OnInitialized{Async}` lifecycle methods](xref:blazor/components/lifecycle#component-initialization-oninitializedasync) of components that are loaded by the first page requested from the app. For more information, see [Debugging with Visual Studio for Mac](/visualstudio/mac/debugging). @@ -406,7 +406,7 @@ Available scenarios include: For now, you *can't*: * Break on unhandled exceptions. -* Hit breakpoints during app startup before the debug proxy is running. This includes breakpoints in `Program.Main` (`Program.cs`) and breakpoints in the [`OnInitialized{Async}` lifecycle methods](xref:blazor/components/lifecycle#component-initialization-oninitializedasync) of components that are loaded by the first page requested from the app. +* Hit breakpoints during app startup before the debug proxy is running. This includes breakpoints in `Program.cs` and breakpoints in the [`OnInitialized{Async}` lifecycle methods](xref:blazor/components/lifecycle#component-initialization-oninitializedasync) of components that are loaded by the first page requested from the app. * Debug in non-local scenarios (for example, [Windows Subsystem for Linux (WSL)](/windows/wsl/) or [Visual Studio Codespaces](/visualstudio/devinit/devinit-and-codespaces)). * Automatically rebuild the backend `*Server*` app of a hosted Blazor WebAssembly solution during debugging, for example by running the app with [`dotnet watch run`](xref:tutorials/dotnet-watch). @@ -477,7 +477,7 @@ While debugging a Blazor WebAssembly app, you can also debug server code: 1. Press F5 again to let execution continue and see the weather forecast table rendered in the browser. > [!NOTE] -> Breakpoints are **not** hit during app startup before the debug proxy is running. This includes breakpoints in `Program.Main` (`Program.cs`) and breakpoints in the [`OnInitialized{Async}` lifecycle methods](xref:blazor/components/lifecycle#component-initialization-oninitializedasync) of components that are loaded by the first page requested from the app. +> Breakpoints are **not** hit during app startup before the debug proxy is running. This includes breakpoints in `Program.cs` and breakpoints in the [`OnInitialized{Async}` lifecycle methods](xref:blazor/components/lifecycle#component-initialization-oninitializedasync) of components that are loaded by the first page requested from the app. If the app is hosted at a different [app base path](xref:blazor/host-and-deploy/index#app-base-path) than `/`, update the following properties in `Properties/launchSettings.json` to reflect the app's base path: @@ -558,7 +558,7 @@ For information on configuring VS Code assets in the `.vscode` folder, see the * 1. In the browser, navigate to `Counter` page and select the **Click me** button to hit the breakpoint. > [!NOTE] -> Breakpoints are **not** hit during app startup before the debug proxy is running. This includes breakpoints in `Program.Main` (`Program.cs`) and breakpoints in the [`OnInitialized{Async}` lifecycle methods](xref:blazor/components/lifecycle#component-initialization-oninitializedasync) of components that are loaded by the first page requested from the app. +> Breakpoints are **not** hit during app startup before the debug proxy is running. This includes breakpoints in `Program.cs` and breakpoints in the [`OnInitialized{Async}` lifecycle methods](xref:blazor/components/lifecycle#component-initialization-oninitializedasync) of components that are loaded by the first page requested from the app. ## Debug hosted Blazor WebAssembly @@ -699,7 +699,7 @@ While debugging a Blazor WebAssembly app, you can also debug server code: 1. Press + again to let execution continue and see the weather forecast table rendered in the browser. > [!NOTE] -> Breakpoints are **not** hit during app startup before the debug proxy is running. This includes breakpoints in `Program.Main` (`Program.cs`) and breakpoints in the [`OnInitialized{Async}` lifecycle methods](xref:blazor/components/lifecycle#component-initialization-oninitializedasync) of components that are loaded by the first page requested from the app. +> Breakpoints are **not** hit during app startup before the debug proxy is running. This includes breakpoints in `Program.cs` and breakpoints in the [`OnInitialized{Async}` lifecycle methods](xref:blazor/components/lifecycle#component-initialization-oninitializedasync) of components that are loaded by the first page requested from the app. For more information, see [Debugging with Visual Studio for Mac](/visualstudio/mac/debugging). @@ -829,7 +829,7 @@ Available scenarios include: For now, you *can't*: * Break on unhandled exceptions. -* Hit breakpoints during app startup before the debug proxy is running. This includes breakpoints in `Program.Main` (`Program.cs`) and breakpoints in the [`OnInitialized{Async}` lifecycle methods](xref:blazor/components/lifecycle#component-initialization-oninitializedasync) of components that are loaded by the first page requested from the app. +* Hit breakpoints during app startup before the debug proxy is running. This includes breakpoints in `Program.cs` and breakpoints in the [`OnInitialized{Async}` lifecycle methods](xref:blazor/components/lifecycle#component-initialization-oninitializedasync) of components that are loaded by the first page requested from the app. * Debug in non-local scenarios (for example, [Windows Subsystem for Linux (WSL)](/windows/wsl/) or [Visual Studio Codespaces](/visualstudio/devinit/devinit-and-codespaces)). * Automatically rebuild the backend `*Server*` app of a hosted Blazor WebAssembly solution during debugging, for example by running the app with [`dotnet watch run`](xref:tutorials/dotnet-watch). @@ -900,7 +900,7 @@ While debugging a Blazor WebAssembly app, you can also debug server code: 1. Press F5 again to let execution continue and see the weather forecast table rendered in the browser. > [!NOTE] -> Breakpoints are **not** hit during app startup before the debug proxy is running. This includes breakpoints in `Program.Main` (`Program.cs`) and breakpoints in the [`OnInitialized{Async}` lifecycle methods](xref:blazor/components/lifecycle#component-initialization-oninitializedasync) of components that are loaded by the first page requested from the app. +> Breakpoints are **not** hit during app startup before the debug proxy is running. This includes breakpoints in `Program.cs` and breakpoints in the [`OnInitialized{Async}` lifecycle methods](xref:blazor/components/lifecycle#component-initialization-oninitializedasync) of components that are loaded by the first page requested from the app. If the app is hosted at a different [app base path](xref:blazor/host-and-deploy/index#app-base-path) than `/`, update the following properties in `Properties/launchSettings.json` to reflect the app's base path: @@ -981,7 +981,7 @@ For information on configuring VS Code assets in the `.vscode` folder, see the * 1. In the browser, navigate to `Counter` page and select the **Click me** button to hit the breakpoint. > [!NOTE] -> Breakpoints are **not** hit during app startup before the debug proxy is running. This includes breakpoints in `Program.Main` (`Program.cs`) and breakpoints in the [`OnInitialized{Async}` lifecycle methods](xref:blazor/components/lifecycle#component-initialization-oninitializedasync) of components that are loaded by the first page requested from the app. +> Breakpoints are **not** hit during app startup before the debug proxy is running. This includes breakpoints in `Program.cs` and breakpoints in the [`OnInitialized{Async}` lifecycle methods](xref:blazor/components/lifecycle#component-initialization-oninitializedasync) of components that are loaded by the first page requested from the app. ## Debug hosted Blazor WebAssembly @@ -1122,7 +1122,7 @@ While debugging a Blazor WebAssembly app, you can also debug server code: 1. Press + again to let execution continue and see the weather forecast table rendered in the browser. > [!NOTE] -> Breakpoints are **not** hit during app startup before the debug proxy is running. This includes breakpoints in `Program.Main` (`Program.cs`) and breakpoints in the [`OnInitialized{Async}` lifecycle methods](xref:blazor/components/lifecycle#component-initialization-oninitializedasync) of components that are loaded by the first page requested from the app. +> Breakpoints are **not** hit during app startup before the debug proxy is running. This includes breakpoints in `Program.cs` and breakpoints in the [`OnInitialized{Async}` lifecycle methods](xref:blazor/components/lifecycle#component-initialization-oninitializedasync) of components that are loaded by the first page requested from the app. For more information, see [Debugging with Visual Studio for Mac](/visualstudio/mac/debugging). diff --git a/aspnetcore/blazor/file-uploads.md b/aspnetcore/blazor/file-uploads.md index f33a9202af56..3559295b32a5 100644 --- a/aspnetcore/blazor/file-uploads.md +++ b/aspnetcore/blazor/file-uploads.md @@ -142,10 +142,10 @@ The following example demonstrates uploading files from a Blazor Server app to a In the Blazor Server app, add and related services that allow the app to create instances. -In `Startup.ConfigureServices` of `Startup.cs`: +In `Program.cs`: ```csharp -services.AddHttpClient(); +builder.Services.AddHttpClient(); ``` For more information, see . diff --git a/aspnetcore/blazor/forms-validation.md b/aspnetcore/blazor/forms-validation.md index f2d35626424e..873d0099be63 100644 --- a/aspnetcore/blazor/forms-validation.md +++ b/aspnetcore/blazor/forms-validation.md @@ -506,18 +506,18 @@ If the server API returns the preceding default JSON response, it's possible for } ``` -To modify the server API's response to make it only return the validation errors, change the delegate that's invoked on actions that are annotated with in `Startup.ConfigureServices`. For the API endpoint (`/StarshipValidation`), return a with the . For any other API endpoints, preserve the default behavior by returning the object result with a new . +To modify the server API's response to make it only return the validation errors, change the delegate that's invoked on actions that are annotated with in `Program.cs`. For the API endpoint (`/StarshipValidation`), return a with the . For any other API endpoints, preserve the default behavior by returning the object result with a new . -Add the namespace to the top of the `Startup.cs` file in the **`Server`** app: +Add the namespace to the top of the `Program.cs` file in the **`Server`** app: ```csharp using Microsoft.AspNetCore.Mvc; ``` -In `Startup.ConfigureServices`, locate the extension method and add the following call to : +In `Program.cs`, locate the extension method and add the following call to : ```csharp -services.AddControllersWithViews() +builder.Services.AddControllersWithViews() .ConfigureApiBehaviorOptions(options => { options.InvalidModelStateResponseFactory = context => diff --git a/aspnetcore/blazor/fundamentals/configuration.md b/aspnetcore/blazor/fundamentals/configuration.md index 9c844f6a66f6..19abdb41c330 100644 --- a/aspnetcore/blazor/fundamentals/configuration.md +++ b/aspnetcore/blazor/fundamentals/configuration.md @@ -78,7 +78,7 @@ Add the namespace for service registration to use the client to read the file: +In `Program.cs`, modify the existing service registration to use the client to read the file: ```csharp var http = new HttpClient() @@ -96,7 +96,7 @@ builder.Configuration.AddJsonStream(stream); ## Memory Configuration Source -The following example uses a in `Program.Main` to supply additional configuration. +The following example uses a in `Program.cs` to supply additional configuration. Add the namespace for to `Program.cs`: @@ -104,7 +104,7 @@ Add the namespace for () @@ -178,7 +178,7 @@ Provide authentication configuration in an app settings file. } ``` -Load the configuration for an Identity provider with in `Program.Main`. The following example loads configuration for an [OIDC provider](xref:blazor/security/webassembly/standalone-with-authentication-library). +Load the configuration for an Identity provider with in `Program.cs`. The following example loads configuration for an [OIDC provider](xref:blazor/security/webassembly/standalone-with-authentication-library). `Program.cs`: @@ -197,7 +197,7 @@ Add a package reference for [`Microsoft.Extensions.Logging.Configuration`](https In the preceding example, the `{VERSION}` placeholder is the package's version. Package versions are found at [NuGet.org](https://www.nuget.org/packages/Microsoft.Extensions.Logging.Configuration). -In the app settings file, provide logging configuration. The logging configuration is loaded in `Program.Main`. +In the app settings file, provide logging configuration. The logging configuration is loaded in `Program.cs`. `wwwroot/appsettings.json`: @@ -219,7 +219,7 @@ Add the namespace for in `Program.Main`. +Read host builder configuration from in `Program.cs`. -In `Program.Main` of `Program.cs`: +In `Program.cs`: ```csharp var hostname = builder.Configuration["HostName"]; @@ -314,7 +314,7 @@ Add the namespace for service registration to use the client to read the file: +In `Program.cs`, modify the existing service registration to use the client to read the file: ```csharp var http = new HttpClient() @@ -332,7 +332,7 @@ builder.Configuration.AddJsonStream(stream); ## Memory Configuration Source -The following example uses a in `Program.Main` to supply additional configuration. +The following example uses a in `Program.cs` to supply additional configuration. Add the namespace for to `Program.cs`: @@ -340,7 +340,7 @@ Add the namespace for () @@ -414,7 +414,7 @@ Provide authentication configuration in an app settings file. } ``` -Load the configuration for an Identity provider with in `Program.Main`. The following example loads configuration for an [OIDC provider](xref:blazor/security/webassembly/standalone-with-authentication-library). +Load the configuration for an Identity provider with in `Program.cs`. The following example loads configuration for an [OIDC provider](xref:blazor/security/webassembly/standalone-with-authentication-library). `Program.cs`: @@ -433,7 +433,7 @@ Add a package reference for [`Microsoft.Extensions.Logging.Configuration`](https In the preceding example, the `{VERSION}` placeholder is the package's version. Package versions are found at [NuGet.org](https://www.nuget.org/packages/Microsoft.Extensions.Logging.Configuration). -In the app settings file, provide logging configuration. The logging configuration is loaded in `Program.Main`. +In the app settings file, provide logging configuration. The logging configuration is loaded in `Program.cs`. `wwwroot/appsettings.json`: @@ -455,7 +455,7 @@ Add the namespace for in `Program.Main`. +Read host builder configuration from in `Program.cs`. -In `Program.Main` of `Program.cs`: +In `Program.cs`: ```csharp var hostname = builder.Configuration["HostName"]; @@ -550,7 +550,7 @@ Add the namespace for service registration to use the client to read the file: +In `Program.cs`, modify the existing service registration to use the client to read the file: ```csharp var http = new HttpClient() @@ -568,7 +568,7 @@ builder.Configuration.AddJsonStream(stream); ## Memory Configuration Source -The following example uses a in `Program.Main` to supply additional configuration. +The following example uses a in `Program.cs` to supply additional configuration. Add the namespace for to `Program.cs`: @@ -576,7 +576,7 @@ Add the namespace for () @@ -650,7 +650,7 @@ Provide authentication configuration in an app settings file. } ``` -Load the configuration for an Identity provider with in `Program.Main`. The following example loads configuration for an [OIDC provider](xref:blazor/security/webassembly/standalone-with-authentication-library). +Load the configuration for an Identity provider with in `Program.cs`. The following example loads configuration for an [OIDC provider](xref:blazor/security/webassembly/standalone-with-authentication-library). `Program.cs`: @@ -669,7 +669,7 @@ Add a package reference for [`Microsoft.Extensions.Logging.Configuration`](https In the preceding example, the `{VERSION}` placeholder is the package's version. Package versions are found at [NuGet.org](https://www.nuget.org/packages/Microsoft.Extensions.Logging.Configuration). -In the app settings file, provide logging configuration. The logging configuration is loaded in `Program.Main`. +In the app settings file, provide logging configuration. The logging configuration is loaded in `Program.cs`. `wwwroot/appsettings.json`: @@ -691,7 +691,7 @@ Add the namespace for in `Program.Main`. +Read host builder configuration from in `Program.cs`. -In `Program.Main` of `Program.cs`: +In `Program.cs`: ```csharp var hostname = builder.Configuration["HostName"]; diff --git a/aspnetcore/blazor/fundamentals/dependency-injection.md b/aspnetcore/blazor/fundamentals/dependency-injection.md index d5d40ff2f854..c9f6263f32b9 100644 --- a/aspnetcore/blazor/fundamentals/dependency-injection.md +++ b/aspnetcore/blazor/fundamentals/dependency-injection.md @@ -37,92 +37,68 @@ A custom service provider doesn't automatically provide the default services lis ::: zone pivot="webassembly" -Configure services for the app's service collection in the `Program.Main` method of `Program.cs`. In the following example, the `MyDependency` implementation is registered for `IMyDependency`: +Configure services for the app's service collection in `Program.cs`. In the following example, the `MyDependency` implementation is registered for `IMyDependency`: ```csharp -public class Program -{ - public static async Task Main(string[] args) - { - var builder = WebAssemblyHostBuilder.CreateDefault(args); - ... - builder.Services.AddSingleton(); - ... +var builder = WebAssemblyHostBuilder.CreateDefault(args); +... +builder.Services.AddSingleton(); +... - await builder.Build().RunAsync(); - } -} +await builder.Build().RunAsync(); ``` After the host is built, services are available from the root DI scope before any components are rendered. This can be useful for running initialization logic before rendering content: ```csharp -public class Program -{ - public static async Task Main(string[] args) - { - var builder = WebAssemblyHostBuilder.CreateDefault(args); - ... - builder.Services.AddSingleton(); - ... +var builder = WebAssemblyHostBuilder.CreateDefault(args); +... +builder.Services.AddSingleton(); +... - var host = builder.Build(); +var host = builder.Build(); - var weatherService = host.Services.GetRequiredService(); - await weatherService.InitializeWeatherAsync(); +var weatherService = host.Services.GetRequiredService(); +await weatherService.InitializeWeatherAsync(); - await host.RunAsync(); - } -} +await host.RunAsync(); ``` The host provides a central configuration instance for the app. Building on the preceding example, the weather service's URL is passed from a default configuration source (for example, `appsettings.json`) to `InitializeWeatherAsync`: ```csharp -public class Program -{ - public static async Task Main(string[] args) - { - var builder = WebAssemblyHostBuilder.CreateDefault(args); - ... - builder.Services.AddSingleton(); - ... +var builder = WebAssemblyHostBuilder.CreateDefault(args); +... +builder.Services.AddSingleton(); +... - var host = builder.Build(); +var host = builder.Build(); - var weatherService = host.Services.GetRequiredService(); - await weatherService.InitializeWeatherAsync( - host.Configuration["WeatherServiceUrl"]); +var weatherService = host.Services.GetRequiredService(); +await weatherService.InitializeWeatherAsync( + host.Configuration["WeatherServiceUrl"]); - await host.RunAsync(); - } -} +await host.RunAsync(); ``` ::: zone-end ::: zone pivot="server" -After creating a new app, examine the `Startup.ConfigureServices` method in `Startup.cs`: +After creating a new app, examine part of the `Program.cs` file: ```csharp -using Microsoft.Extensions.DependencyInjection; +var builder = WebApplication.CreateBuilder(args); -... - -public void ConfigureServices(IServiceCollection services) -{ - ... -} +builder.Services.AddRazorPages(); +builder.Services.AddServerSideBlazor(); +builder.Services.AddSingleton(); ``` -The method is passed an , which is a list of [service descriptor](xref:Microsoft.Extensions.DependencyInjection.ServiceDescriptor) objects. Services are added in the `ConfigureServices` method by providing service descriptors to the service collection. The following example demonstrates the concept with the `IDataAccess` interface and its concrete implementation `DataAccess`: +The `builder` variable represents a `Microsoft.AspNetCore.Builder.WebApplicationBuilder` with an , which is a list of [service descriptor](xref:Microsoft.Extensions.DependencyInjection.ServiceDescriptor) objects. Services are added by providing service descriptors to the service collection. The following example demonstrates the concept with the `IDataAccess` interface and its concrete implementation `DataAccess`: ```csharp -public void ConfigureServices(IServiceCollection services) -{ - services.AddSingleton(); -} +builder.Services.AddSingleton(); ``` ::: zone-end @@ -253,27 +229,25 @@ The following examples show how to detect disposable transient services in an ap The `TransientDisposable` in the following example is detected (`Program.cs`): ```csharp -public class Program -{ - public static async Task Main(string[] args) +var builder = WebAssemblyHostBuilder.CreateDefault(args); +builder.DetectIncorrectUsageOfTransients(); +builder.RootComponents.Add("#app"); + +builder.Services.AddTransient(); +builder.Services.AddScoped(sp => + new HttpClient { - var builder = WebAssemblyHostBuilder.CreateDefault(args); - builder.DetectIncorrectUsageOfTransients(); - builder.RootComponents.Add("#app"); + BaseAddress = new(builder.HostEnvironment.BaseAddress) + }); - builder.Services.AddTransient(); - builder.Services.AddScoped(sp => - new HttpClient - { - BaseAddress = new(builder.HostEnvironment.BaseAddress) - }); +var host = builder.Build(); +host.EnableTransientDisposableDetection(); +await host.RunAsync(); +``` - var host = builder.Build(); - host.EnableTransientDisposableDetection(); - await host.RunAsync(); - } -} +`TransientDisposable.cs`: +```csharp public class TransientDisposable : IDisposable { public void Dispose() => throw new NotImplementedException(); @@ -288,37 +262,15 @@ public class TransientDisposable : IDisposable [!code-csharp[](~/blazor/samples/6.0/BlazorSample_Server/dependency-injection/DetectIncorrectUsagesOfTransientDisposables.cs)] -Add the namespace for to `Program.cs`: - -```csharp -using Microsoft.Extensions.DependencyInjection; -``` - -In `Program.CreateHostBuilder` of `Program.cs`: +In `Program.cs`: ```csharp -public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .DetectIncorrectUsageOfTransients() - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }); +app.DetectIncorrectUsageOfTransients(); ``` -The `TransientDependency` in the following example is detected (`Startup.cs`): +`TransitiveTransientDisposableDependency.cs`: ```csharp -public void ConfigureServices(IServiceCollection services) -{ - services.AddRazorPages(); - services.AddServerSideBlazor(); - services.AddSingleton(); - services.AddTransient(); - services.AddTransient(); -} - public class TransitiveTransientDisposableDependency : ITransitiveTransientDisposableDependency, IDisposable { @@ -343,6 +295,17 @@ public class TransientDependency } ``` +The `TransientDependency` in the following example is detected (`Program.cs`): + +```csharp +builder.Services.AddRazorPages(); +builder.Services.AddServerSideBlazor(); +builder.Services.AddSingleton(); +builder.Services.AddTransient(); +builder.Services.AddTransient(); +``` + ::: zone-end The app can register transient disposables without throwing an exception. However, attempting to resolve a transient disposable results in an , as the following example shows. @@ -391,7 +354,7 @@ A custom service provider doesn't automatically provide the default services lis ::: zone pivot="webassembly" -Configure services for the app's service collection in the `Program.Main` method of `Program.cs`. In the following example, the `MyDependency` implementation is registered for `IMyDependency`: +Configure services for the app's service collection in `Program.cs`. In the following example, the `MyDependency` implementation is registered for `IMyDependency`: ```csharp public class Program @@ -745,7 +708,7 @@ A custom service provider doesn't automatically provide the default services lis ::: zone pivot="webassembly" -Configure services for the app's service collection in the `Program.Main` method of `Program.cs`. In the following example, the `MyDependency` implementation is registered for `IMyDependency`: +Configure services for the app's service collection in `Program.cs`. In the following example, the `MyDependency` implementation is registered for `IMyDependency`: ```csharp public class Program diff --git a/aspnetcore/blazor/fundamentals/environments.md b/aspnetcore/blazor/fundamentals/environments.md index f06565b33a46..82247bc7e403 100644 --- a/aspnetcore/blazor/fundamentals/environments.md +++ b/aspnetcore/blazor/fundamentals/environments.md @@ -81,7 +81,7 @@ Obtain the app's environment in a component by injecting exposes the through the property, which enables environment-specific logic in host builder code. -In `Program.Main` of `Program.cs`: +In `Program.cs`: ```csharp if (builder.HostEnvironment.Environment == "Custom") @@ -97,7 +97,7 @@ The following convenience extension methods provided through * -In `Program.Main` of `Program.cs`: +In `Program.cs`: ```csharp if (builder.HostEnvironment.IsStaging()) @@ -190,7 +190,7 @@ Obtain the app's environment in a component by injecting exposes the through the property, which enables environment-specific logic in host builder code. -In `Program.Main` of `Program.cs`: +In `Program.cs`: ```csharp if (builder.HostEnvironment.Environment == "Custom") @@ -206,7 +206,7 @@ The following convenience extension methods provided through * -In `Program.Main` of `Program.cs`: +In `Program.cs`: ```csharp if (builder.HostEnvironment.IsStaging()) @@ -273,7 +273,7 @@ Obtain the app's environment in a component by injecting exposes the through the property, which enables environment-specific logic in host builder code. -In `Program.Main` of `Program.cs`: +In `Program.cs`: ```csharp if (builder.HostEnvironment.Environment == "Custom") @@ -289,7 +289,7 @@ The following convenience extension methods provided through * -In `Program.Main` of `Program.cs`: +In `Program.cs`: ```csharp if (builder.HostEnvironment.IsStaging()) diff --git a/aspnetcore/blazor/fundamentals/logging.md b/aspnetcore/blazor/fundamentals/logging.md index 606139c6b156..f891933fccc1 100644 --- a/aspnetcore/blazor/fundamentals/logging.md +++ b/aspnetcore/blazor/fundamentals/logging.md @@ -24,7 +24,7 @@ Add the namespace for and add the custom logging provider: +In `Program.cs`, set the minimum logging level with and add the custom logging provider: ```csharp var builder = WebAssemblyHostBuilder.CreateDefault(args); @@ -108,7 +108,7 @@ Add the namespace for and add the custom logging provider: +In `Program.cs`, set the minimum logging level with and add the custom logging provider: ```csharp var builder = WebAssemblyHostBuilder.CreateDefault(args); @@ -192,7 +192,7 @@ Add the namespace for and add the custom logging provider: +In `Program.cs`, set the minimum logging level with and add the custom logging provider: ```csharp var builder = WebAssemblyHostBuilder.CreateDefault(args); diff --git a/aspnetcore/blazor/fundamentals/routing.md b/aspnetcore/blazor/fundamentals/routing.md index 3ed2f2a0a4ed..2a181a0fbe93 100644 --- a/aspnetcore/blazor/fundamentals/routing.md +++ b/aspnetcore/blazor/fundamentals/routing.md @@ -177,20 +177,16 @@ Consider the following `Example` component that can receive a route parameter fr [!code-razor[](~/blazor/samples/6.0/BlazorSample_WebAssembly/Pages/routing/Example.razor?highlight=1)] -To permit the **`Server`** app of a hosted Blazor WebAssembly solution to route the request with a dot in the `param` route parameter, add a fallback file route template with the optional parameter in `Startup.Configure`. - -`Startup.cs`: +To permit the **`Server`** app of a hosted Blazor WebAssembly solution to route the request with a dot in the `param` route parameter, add a fallback file route template with the optional parameter in `Program.cs`: ```csharp -endpoints.MapFallbackToFile("/example/{param?}", "index.html"); +app.MapFallbackToFile("/example/{param?}", "index.html"); ``` -To configure a Blazor Server app to route the request with a dot in the `param` route parameter, add a fallback page route template with the optional parameter in `Startup.Configure`. - -`Startup.cs`: +To configure a Blazor Server app to route the request with a dot in the `param` route parameter, add a fallback page route template with the optional parameter in `Program.cs`: ```csharp -endpoints.MapFallbackToPage("/example/{param?}", "/_Host"); +app.MapFallbackToPage("/example/{param?}", "/_Host"); ``` For more information, see . @@ -645,11 +641,9 @@ The following HTML markup is rendered: *This section only applies to Blazor Server apps.* -Blazor Server is integrated into [ASP.NET Core Endpoint Routing](xref:fundamentals/routing). An ASP.NET Core app is configured to accept incoming connections for interactive components with in `Startup.Configure`. - -`Startup.cs`: +Blazor Server is integrated into [ASP.NET Core Endpoint Routing](xref:fundamentals/routing). An ASP.NET Core app is configured to accept incoming connections for interactive components with in `Program.cs`: -[!code-csharp[](~/blazor/samples/6.0/BlazorSample_Server/routing/Startup.cs?highlight=11)] +[!code-csharp[](~/blazor/samples/6.0/BlazorSample_Server/routing/Program.cs)] The typical configuration is to route all requests to a Razor page, which acts as the host for the server-side part of the Blazor Server app. By convention, the *host* page is usually named `_Host.cshtml` in the `Pages` folder of the app. diff --git a/aspnetcore/blazor/fundamentals/signalr.md b/aspnetcore/blazor/fundamentals/signalr.md index 604c9fc0361e..43a90f73ce62 100644 --- a/aspnetcore/blazor/fundamentals/signalr.md +++ b/aspnetcore/blazor/fundamentals/signalr.md @@ -96,12 +96,12 @@ Configure the Blazor Server circuit with the | 1 minute | Maximum amount of time the server waits before timing out an asynchronous JavaScript function invocation. | | | 10 | Maximum number of unacknowledged render batches the server keeps in memory per circuit at a given time to support robust reconnection. After reaching the limit, the server stops producing new render batches until one or more batches are acknowledged by the client. | -Configure the options in `Startup.ConfigureServices` with an options delegate to . The following example assigns the default option values shown in the preceding table. Confirm that `Startup.cs` uses the namespace (`using System;`). +Configure the options in `Program.cs` with an options delegate to . The following example assigns the default option values shown in the preceding table. Confirm that `Program.cs` uses the namespace (`using System;`). -`Startup.ConfigureServices`: +In `Program.cs`: ```csharp -services.AddServerSideBlazor(options => +builder.Services.AddServerSideBlazor(options => { options.DetailedErrors = false; options.DisconnectedCircuitMaxRetained = 100; @@ -111,12 +111,12 @@ services.AddServerSideBlazor(options => }); ``` -To configure the , use with . For option descriptions, see . The following example assigns the default option values. Confirm that `Startup.cs` uses the namespace (`using System;`). +To configure the , use with . For option descriptions, see . The following example assigns the default option values. Confirm that `Program.cs` uses the namespace (`using System;`). -`Startup.ConfigureServices`: +In `Program.cs`: ```csharp -services.AddServerSideBlazor() +builder.Services.AddServerSideBlazor() .AddHubOptions(options => { options.ClientTimeoutInterval = TimeSpan.FromSeconds(30); @@ -131,7 +131,7 @@ services.AddServerSideBlazor() ## Blazor Hub endpoint route configuration -In `Startup.Configure`, Blazor Server apps call on the of to map the Blazor to the app's default path. The Blazor Server script (`blazor.server.js`) automatically points to the endpoint created by . +In `Program.cs`, Blazor Server apps call to map the Blazor to the app's default path. The Blazor Server script (`blazor.server.js`) automatically points to the endpoint created by . ## Reflect the connection state in the UI @@ -332,14 +332,10 @@ Blazor Server allows code to define a *circuit handler*, which allows running co Circuit handlers are registered using DI. Scoped instances are created per instance of a circuit. Using the `TrackingCircuitHandler` in the preceding example, a singleton service is created because the state of all circuits must be tracked. -`Startup.cs`: +`Program.cs`: ```csharp -public void ConfigureServices(IServiceCollection services) -{ - ... - services.AddSingleton(); -} +builder.Services.AddSingleton(); ``` If a custom circuit handler's methods throw an unhandled exception, the exception is fatal to the Blazor Server circuit. To tolerate exceptions in a handler's code or called methods, wrap the code in one or more [`try-catch`](/dotnet/csharp/language-reference/keywords/try-catch) statements with error handling and logging. @@ -354,10 +350,10 @@ We recommend using the [Azure SignalR Service](xref:signalr/scale#azure-signalr- In earlier versions of ASP.NET Core, Long Polling was enabled as a fallback transport for situations in which the WebSockets transport wasn't available. If an app must use Long Polling, make the following changes: -In the app's `Startup.cs` file, replace `endpoints.MapBlazorHub()` with the following code: +In the app's `Program.cs` file, replace `app.MapBlazorHub()` with the following code: ```csharp -endpoints.MapBlazorHub(configureOptions: options => +app.MapBlazorHub(configureOptions: options => { options.Transports = HttpTransportType.WebSockets | HttpTransportType.LongPolling; diff --git a/aspnetcore/blazor/fundamentals/static-files.md b/aspnetcore/blazor/fundamentals/static-files.md index bf9a9355b09c..ab7ff6d9558d 100644 --- a/aspnetcore/blazor/fundamentals/static-files.md +++ b/aspnetcore/blazor/fundamentals/static-files.md @@ -17,7 +17,7 @@ uid: blazor/fundamentals/static-files To create additional file mappings with a or configure other , use **one** of the following approaches. In the following examples, the `{EXTENSION}` placeholder is the file extension, and the `{CONTENT TYPE}` placeholder is the content type. -* Configure options through [dependency injection (DI)](xref:blazor/fundamentals/dependency-injection) in `Startup.ConfigureServices` (`Startup.cs`) using : +* Configure options through [dependency injection (DI)](xref:blazor/fundamentals/dependency-injection) in `Program.cs` using : ```csharp using Microsoft.AspNetCore.StaticFiles; @@ -27,7 +27,7 @@ To create additional file mappings with a (options => + builder.Services.Configure(options => { options.ContentTypeProvider = provider; }); @@ -35,7 +35,7 @@ To create additional file mappings with a in `Startup.Configure` (`Startup.cs`): +* Use two calls to in `Program.cs`: * Configure the custom file provider in the first call with . * The second middleware serves `blazor.server.js`, which uses the default static files configuration provided by the Blazor framework. diff --git a/aspnetcore/blazor/globalization-localization.md b/aspnetcore/blazor/globalization-localization.md index 1a4f0823f790..875a6e1256de 100644 --- a/aspnetcore/blazor/globalization-localization.md +++ b/aspnetcore/blazor/globalization-localization.md @@ -183,13 +183,13 @@ Set the `BlazorWebAssemblyLoadAllGlobalizationData` property to `true` in the ap Blazor Server apps are localized using [Localization Middleware](xref:fundamentals/localization#localization-middleware). Add localization services to the app with . -In `Startup.ConfigureServices` (`Startup.cs`): +In `Program.cs`: ```csharp -services.AddLocalization(); +builder.Services.AddLocalization(); ``` -Specify the app's supported cultures in `Startup.Configure` (`Startup.cs`) immediately after Routing Middleware is added to the processing pipeline. The following example configures supported cultures for United States English and Chilean Spanish: +Specify the app's supported cultures in `Program.cs` immediately after Routing Middleware is added to the processing pipeline. The following example configures supported cultures for United States English and Chilean Spanish: ```csharp app.UseRequestLocalization(new RequestLocalizationOptions() @@ -197,7 +197,7 @@ app.UseRequestLocalization(new RequestLocalizationOptions() .AddSupportedUICultures(new[] { "en-US", "es-CL" })); ``` -For information on ordering the Localization Middleware in the middleware pipeline of `Startup.Configure`, see . +For information on ordering the Localization Middleware in the middleware pipeline of `Program.cs`, see . ::: zone-end @@ -248,7 +248,7 @@ The app's culture can be set in JavaScript when Blazor starts with the `applicat The value for `applicationCulture` must conform to the [BCP-47 language tag format](https://www.rfc-editor.org/info/bcp47). For more information on Blazor startup, see . -An alternative to setting the culture Blazor's start option is to set the culture in C# code. Set and in `Program.Main` (`Program.cs`). +An alternative to setting the culture Blazor's start option is to set the culture in C# code. Set and in `Program.cs`. Add the namespace to `Program.cs`: @@ -269,13 +269,13 @@ CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("en-US"); Blazor Server apps are localized using [Localization Middleware](xref:fundamentals/localization#localization-middleware). Add localization services to the app with . -In `Startup.ConfigureServices` (`Startup.cs`): +In `Program.cs`: ```csharp -services.AddLocalization(); +builder.Services.AddLocalization(); ``` -Specify the static culture in `Startup.Configure` (`Startup.cs`) immediately after Routing Middleware is added to the processing pipeline. The following example configures United States English: +Specify the static culture in `Program.cs` immediately after Routing Middleware is added to the processing pipeline. The following example configures United States English: ```csharp app.UseRequestLocalization("en-US"); @@ -283,7 +283,7 @@ app.UseRequestLocalization("en-US"); The culture value for must conform to the [BCP-47 language tag format](https://www.rfc-editor.org/info/bcp47). -For information on ordering the Localization Middleware in the middleware pipeline of `Startup.Configure`, see . +For information on ordering the Localization Middleware in the middleware pipeline of `Program.cs`, see . ::: zone-end @@ -347,10 +347,10 @@ using System.Globalization; using Microsoft.JSInterop; ``` -Remove the following line from `Program.Main`: +Remove the following line from `Program.cs`: ```diff --await builder.Build().RunAsync(); +- await builder.Build().RunAsync(); ``` Replace the preceding line with the following code. The code adds Blazor's localization service to the app's service collection with and uses [JS interop](xref:blazor/js-interop/call-javascript-from-dotnet) to call into JS and retrieve the user's culture selection from local storage. If local storage doesn't contain a culture for the user, the code sets a default value of United States English (`en-US`). @@ -452,15 +452,15 @@ The `{VERSION}` placeholder in the preceding package reference is the version of Blazor Server apps are localized using [Localization Middleware](xref:fundamentals/localization#localization-middleware). Add localization services to the app with . -In `Startup.ConfigureServices` (`Startup.cs`): +In `Program.cs`: ```csharp -services.AddLocalization(); +builder.Services.AddLocalization(); ``` Set the app's default and supported cultures with . -In `Startup.Configure` immediately after Routing Middleware is added to the processing pipeline: +In `Program.cs` immediately after Routing Middleware is added to the processing pipeline: ```csharp var supportedCultures = new[] { "en-US", "es-CL" }; @@ -472,7 +472,7 @@ var localizationOptions = new RequestLocalizationOptions() app.UseRequestLocalization(localizationOptions); ``` -For information on ordering the Localization Middleware in the middleware pipeline of `Startup.Configure`, see . +For information on ordering the Localization Middleware in the middleware pipeline of `Program.cs`, see . The following example shows how to set the current culture in a cookie that can be read by the Localization Middleware. @@ -496,31 +496,28 @@ Immediately after the opening `` tag of `Pages/_Layout.cshtml`, add the fo } ``` -For information on ordering the Localization Middleware in the middleware pipeline of `Startup.Configure`, see . +For information on ordering the Localization Middleware in the middleware pipeline of `Program.cs`, see . If the app isn't configured to process controller actions: -* Add MVC services by calling on the service collection in `Startup.ConfigureServices`: +* Add MVC services by calling on the service collection in `Program.cs`: ```csharp - services.AddControllers(); + builder.Services.AddControllers(); ``` -* Add controller endpoint routing in `Startup.Configure` by calling on the : +* Add controller endpoint routing in `Program.cs` by calling on the : ```csharp - endpoints.MapControllers(); + app.MapControllers(); ``` The following example shows the call to after the line is added: - ```diff - app.UseEndpoints(endpoints => - { - + endpoints.MapControllers(); - endpoints.MapBlazorHub(); - endpoints.MapFallbackToPage("/_Host"); - }); + ```csharp + app.MapControllers(); + app.MapBlazorHub(); + app.MapFallbackToPage("/_Host"); ``` To provide UI to allow a user to select a culture, use a *redirect-based approach* with a localization cookie. The app persists the user's selected culture via a redirect to a controller. The controller sets the user's selected culture into a cookie and redirects the user back to the original URI. The process is similar to what happens in a web app when a user attempts to access a secure resource, where the user is redirected to a sign-in page and then redirected back to the original resource. @@ -638,13 +635,13 @@ Set the `BlazorWebAssemblyLoadAllGlobalizationData` property to `true` in the ap ``` -In `Program.Main` (`Program.cs`), add namespace the namespace for to the top of the file: +In `Program.cs`, add namespace the namespace for to the top of the file: ```csharp using System.Globalization; ``` -Add Blazor's localization service to the app's service collection with in `Program.Main`: +Add Blazor's localization service to the app's service collection with in `Program.cs`: ```csharp builder.Services.AddLocalization(); @@ -659,15 +656,15 @@ Use [Localization Middleware](xref:fundamentals/localization#localization-middle If the app doesn't already support culture selection per the [Dynamically set the culture by user preference](#dynamically-set-the-culture-by-user-preference) section of this article: * Add localization services to the app with . -* Specify the app's default and supported cultures in `Startup.Configure` (`Startup.cs`). The following example configures supported cultures for United States English and Chilean Spanish. +* Specify the app's default and supported cultures in `Program.cs`. The following example configures supported cultures for United States English and Chilean Spanish. -In `Startup.ConfigureServices` (`Startup.cs`): +In `Program.cs`: ```csharp -services.AddLocalization(); +builder.Services.AddLocalization(); ``` -In `Startup.Configure` immediately after Routing Middleware is added to the processing pipeline: +In `Program.cs` immediately after Routing Middleware is added to the processing pipeline: ```csharp var supportedCultures = new[] { "en-US", "es-CL" }; @@ -679,7 +676,7 @@ var localizationOptions = new RequestLocalizationOptions() app.UseRequestLocalization(localizationOptions); ``` -For information on ordering the Localization Middleware in the middleware pipeline of `Startup.Configure`, see . +For information on ordering the Localization Middleware in the middleware pipeline of `Program.cs`, see . If the app should localize resources based on storing a user's culture setting, use a localization culture cookie. Use of a cookie ensures that the WebSocket connection can correctly propagate the culture. If localization schemes are based on the URL path or query string, the scheme might not be able to work with [WebSockets](xref:fundamentals/websockets), thus fail to persist the culture. Therefore, the recommended approach is to use a localization culture cookie. See the [Dynamically set the culture by user preference](#dynamically-set-the-culture-by-user-preference) section of this article to see an example Razor expression for the `Pages/_Layout.cshtml` file that persists the user's culture selection. @@ -1134,7 +1131,7 @@ The app's culture can be set in JavaScript when Blazor starts with the `applicat The value for `applicationCulture` must conform to the [BCP-47 language tag format](https://www.rfc-editor.org/info/bcp47). For more information on Blazor startup, see . -An alternative to setting the culture Blazor's start option is to set the culture in C# code. Set and in `Program.Main` (`Program.cs`). +An alternative to setting the culture Blazor's start option is to set the culture in C# code. Set and in `Program.cs`. Add the namespace to `Program.cs`: @@ -1233,10 +1230,10 @@ using System.Globalization; using Microsoft.JSInterop; ``` -Remove the following line from `Program.Main`: +Remove the following line from `Program.cs`: ```diff --await builder.Build().RunAsync(); +- await builder.Build().RunAsync(); ``` Replace the preceding line with the following code. The code adds Blazor's localization service to the app's service collection with and uses [JS interop](xref:blazor/js-interop/call-javascript-from-dotnet) to call into JS and retrieve the user's culture selection from local storage. If local storage doesn't contain a culture for the user, the code sets a default value of United States English (`en-US`). @@ -1524,13 +1521,13 @@ Set the `BlazorWebAssemblyLoadAllGlobalizationData` property to `true` in the ap ``` -In `Program.Main` (`Program.cs`), add namespace the namespace for to the top of the file: +In `Program.cs`, add namespace the namespace for to the top of the file: ```csharp using System.Globalization; ``` -Add Blazor's localization service to the app's service collection with in `Program.Main`: +Add Blazor's localization service to the app's service collection with in `Program.cs`: ```csharp builder.Services.AddLocalization(); @@ -2042,7 +2039,7 @@ using System.Globalization; using Microsoft.JSInterop; ``` -Remove the following line from `Program.Main`: +Remove the following line from `Program.cs`: ```diff -await builder.Build().RunAsync(); @@ -2327,13 +2324,13 @@ The `{VERSION}` placeholder in the preceding package reference is the version of By default, the Intermediate Language (IL) Linker configuration for Blazor WebAssembly apps strips out internationalization information except for locales explicitly requested. For more information, see . -In `Program.Main` (`Program.cs`), add namespace the namespace for to the top of the file: +In `Program.cs`, add namespace the namespace for to the top of the file: ```csharp using System.Globalization; ``` -Add Blazor's localization service to the app's service collection with in `Program.Main`: +Add Blazor's localization service to the app's service collection with in `Program.cs`: ```csharp builder.Services.AddLocalization(); diff --git a/aspnetcore/blazor/host-and-deploy/index.md b/aspnetcore/blazor/host-and-deploy/index.md index 3f83aa1361ae..2572a00af9a2 100644 --- a/aspnetcore/blazor/host-and-deploy/index.md +++ b/aspnetcore/blazor/host-and-deploy/index.md @@ -76,7 +76,7 @@ Blazor Server (`Pages/_Layout.cshtml`): ``` -Blazor Server apps additionally set the server-side base path by calling in the app's request pipeline of `Startup.Configure`: +Blazor Server apps additionally set the server-side base path by calling in the app's request pipeline of `Program.cs`: ```csharp app.UsePathBase("/CoolApp"); @@ -104,16 +104,16 @@ The Blazor WebAssembly app responds locally at `http://localhost:port/CoolApp`. ### Blazor Server `MapFallbackToPage` configuration -Pass the following path to in `Startup.Configure`: +Pass the following path to in `Program.cs`: ```csharp -endpoints.MapFallbackToPage("/{RELATIVE PATH}/{**path:nonfile}"); +app.MapFallbackToPage("/{RELATIVE PATH}/{**path:nonfile}"); ``` The placeholder `{RELATIVE PATH}` is the non-root path on the server. For example, `CoolApp` is the placeholder segment if the non-root URL to the app is `https://{HOST}:{PORT}/CoolApp/`): ```csharp -endpoints.MapFallbackToPage("/CoolApp/{**path:nonfile}"); +app.MapFallbackToPage("/CoolApp/{**path:nonfile}"); ``` ### Host multiple Blazor WebAssembly apps diff --git a/aspnetcore/blazor/host-and-deploy/server.md b/aspnetcore/blazor/host-and-deploy/server.md index d86f95b9386d..de9a86e0c6b7 100644 --- a/aspnetcore/blazor/host-and-deploy/server.md +++ b/aspnetcore/blazor/host-and-deploy/server.md @@ -66,10 +66,10 @@ We recommend using the [Azure SignalR Service](xref:signalr/scale#azure-signalr- To configure an app for the Azure SignalR Service, the app must support *sticky sessions*, where clients are [redirected back to the same server when prerendering](xref:blazor/hosting-models#connection-to-the-server). The `ServerStickyMode` option or configuration value is set to `Required`. Typically, an app creates the configuration using **_ONE_** of the following approaches: -* `Startup.ConfigureServices`: +* `Program.cs`: ```csharp - services.AddSignalR().AddAzureSignalR(options => + builder.Services.AddSignalR().AddAzureSignalR(options => { options.ServerStickyMode = Microsoft.Azure.SignalR.ServerStickyMode.Required; diff --git a/aspnetcore/blazor/host-and-deploy/webassembly.md b/aspnetcore/blazor/host-and-deploy/webassembly.md index d05b8e1e62d6..b9fe8252ee04 100644 --- a/aspnetcore/blazor/host-and-deploy/webassembly.md +++ b/aspnetcore/blazor/host-and-deploy/webassembly.md @@ -43,7 +43,7 @@ To compile the app to WebAssembly, publish the app. Publishing the `Release` con dotnet publish -c Release ``` -WebAssembly AOT compilation is only performed when the the project is published. AOT compilation isn't used when the project is run during development (`Development` environment) because AOT compilation usually takes several minutes on small projects and potentially much longer for larger projects. Reducing the build time for AOT compilation is under development for future releases of ASP.NET Core. +WebAssembly AOT compilation is only performed when the project is published. AOT compilation isn't used when the project is run during development (`Development` environment) because AOT compilation usually takes several minutes on small projects and potentially much longer for larger projects. Reducing the build time for AOT compilation is under development for future releases of ASP.NET Core. The size of an AOT-compiled Blazor WebAssembly app is generally larger than the size of the app if compiled into .NET IL. Although the size difference depends on the app, most AOT-compiled apps are about twice the size of their IL-compiled versions. This means that using AOT compilation trades off load time performance for runtime performance. Whether this tradeoff is worth using AOT compilation depends on your app. Blazor WebAssembly apps that are CPU intensive generally benefit the most from AOT compilation. @@ -171,7 +171,7 @@ Hosted Blazor solutions can serve multiple Blazor WebAssembly apps. In the following example: * The initial (first) client app is the default client project of a solution created from the Blazor WebAssembly project template. The first client app is accessible in a browser from the URL `/FirstApp` on either port 5001 or with a host of `firstapp.com`. -* A second client app is added to the solution, `SecondBlazorApp.Client`. The second client app is accessible in a browser from the the URL `/SecondApp` on either port 5002 or with a host of `secondapp.com`. +* A second client app is added to the solution, `SecondBlazorApp.Client`. The second client app is accessible in a browser from the URL `/SecondApp` on either port 5002 or with a host of `secondapp.com`. Use an existing hosted Blazor solution or create a new solution from the Blazor Hosted project template: @@ -237,7 +237,7 @@ Use an existing hosted Blazor solution or create a new solution from the Blazor "applicationUrl": "https://localhost:5001;https://localhost:5002", ``` -* In the server app's `Startup.Configure` method (`Startup.cs`), remove the following lines, which appear after the call to : +* In the server app's `Program.cs` file, remove the following lines, which appear after the call to : ```csharp app.UseBlazorFrameworkFiles(); @@ -245,12 +245,9 @@ Use an existing hosted Blazor solution or create a new solution from the Blazor app.UseRouting(); - app.UseEndpoints(endpoints => - { - endpoints.MapRazorPages(); - endpoints.MapControllers(); - endpoints.MapFallbackToFile("index.html"); - }); + app.MapRazorPages(); + app.MapControllers(); + app.MapFallbackToFile("index.html"); ``` Add middleware that maps requests to the client apps. The following example configures the middleware to run when: @@ -321,7 +318,7 @@ Use an existing hosted Blazor solution or create a new solution from the Blazor [Route("SecondApp/[controller]")] ``` - The middleware added to the server app's `Startup.Configure` method earlier modifies incoming requests to `/WeatherForecast` to either `/FirstApp/WeatherForecast` or `/SecondApp/WeatherForecast` depending on the port (5001/5002) or domain (`firstapp.com`/`secondapp.com`). The preceding controller routes are required in order to return weather data from the server app to the client apps. + The middleware added to the server app's request processing pipeline earlier modifies incoming requests to `/WeatherForecast` to either `/FirstApp/WeatherForecast` or `/SecondApp/WeatherForecast` depending on the port (5001/5002) or domain (`firstapp.com`/`secondapp.com`). The preceding controller routes are required in order to return weather data from the server app to the client apps. ### Static assets and class libraries for multiple Blazor WebAssembly apps @@ -978,7 +975,7 @@ Hosted Blazor solutions can serve multiple Blazor WebAssembly apps. In the following example: * The initial (first) client app is the default client project of a solution created from the Blazor WebAssembly project template. The first client app is accessible in a browser from the URL `/FirstApp` on either port 5001 or with a host of `firstapp.com`. -* A second client app is added to the solution, `SecondBlazorApp.Client`. The second client app is accessible in a browser from the the URL `/SecondApp` on either port 5002 or with a host of `secondapp.com`. +* A second client app is added to the solution, `SecondBlazorApp.Client`. The second client app is accessible in a browser from the URL `/SecondApp` on either port 5002 or with a host of `secondapp.com`. Use an existing hosted Blazor solution or create a new solution from the Blazor Hosted project template: @@ -1785,7 +1782,7 @@ Hosted Blazor solutions can serve multiple Blazor WebAssembly apps. In the following example: * The initial (first) client app is the default client project of a solution created from the Blazor WebAssembly project template. The first client app is accessible in a browser from the URL `/FirstApp` on either port 5001 or with a host of `firstapp.com`. -* A second client app is added to the solution, `SecondBlazorApp.Client`. The second client app is accessible in a browser from the the URL `/SecondApp` on either port 5002 or with a host of `secondapp.com`. +* A second client app is added to the solution, `SecondBlazorApp.Client`. The second client app is accessible in a browser from the URL `/SecondApp` on either port 5002 or with a host of `secondapp.com`. Use an existing hosted Blazor solution or create a new solution from the Blazor Hosted project template: diff --git a/aspnetcore/blazor/includes/js-interop/size-limits.md b/aspnetcore/blazor/includes/js-interop/size-limits.md index b0398dd27345..2f51c5e6b383 100644 --- a/aspnetcore/blazor/includes/js-interop/size-limits.md +++ b/aspnetcore/blazor/includes/js-interop/size-limits.md @@ -31,7 +31,14 @@ Error: > System.IO.InvalidDataException: The maximum message size of 32768B was exceeded. The message size can be configured in AddHubOptions. -Increase the limit by setting in `Startup.ConfigureServices`. The following example sets the maximum receive message size to 64 KB (64 * 1024): +Increase the limit by setting in `Program.cs`. The following example sets the maximum receive message size to 64 KB (64 * 1024) in ASP.NET Core 6.0 or later: + +```csharp +builder.Services.AddServerSideBlazor() + .AddHubOptions(options => options.MaximumReceiveMessageSize = 64 * 1024); +``` + +In `Startup.ConfigureServices` for versions of ASP.NET Core earlier than 6.0: ```csharp services.AddServerSideBlazor() diff --git a/aspnetcore/blazor/includes/state-container.md b/aspnetcore/blazor/includes/state-container.md index 296bb18ce13b..433ef90a3ae1 100644 --- a/aspnetcore/blazor/includes/state-container.md +++ b/aspnetcore/blazor/includes/state-container.md @@ -31,13 +31,19 @@ public class StateContainer } ``` -In `Program.Main` (Blazor WebAssembly): +In `Program.cs` (Blazor WebAssembly): ```csharp builder.Services.AddSingleton(); ``` -In `Startup.ConfigureServices` (Blazor Server): +In `Program.cs` (Blazor Server) in ASP.NET Core 6.0 or later: + +```csharp +builder.Services.AddScoped(); +``` + +In `Startup.ConfigureServices` (Blazor Server) in versions of ASP.NET Core earlier than 6.0: ```csharp services.AddScoped(); diff --git a/aspnetcore/blazor/javascript-interoperability/call-javascript-from-dotnet.md b/aspnetcore/blazor/javascript-interoperability/call-javascript-from-dotnet.md index 08045fd6af9b..4a928624d7d3 100644 --- a/aspnetcore/blazor/javascript-interoperability/call-javascript-from-dotnet.md +++ b/aspnetcore/blazor/javascript-interoperability/call-javascript-from-dotnet.md @@ -412,10 +412,10 @@ In the preceding example, the namespace of the app is `BlazorSample` with shared In Blazor Server apps, JavaScript (JS) interop may fail due to networking errors and should be treated as unreliable. By default, Blazor Server apps use a one minute timeout for JS interop calls. If an app can tolerate a more aggressive timeout, set the timeout using one of the following approaches. -Set a global timeout in the `Startup.ConfigureServices` method of `Startup.cs` with : +Set a global timeout in the `Program.cs` with : ```csharp -services.AddServerSideBlazor( +builder.Services.AddServerSideBlazor( options => options.JSInteropDefaultCallTimeout = {TIMEOUT}); ``` diff --git a/aspnetcore/blazor/project-structure.md b/aspnetcore/blazor/project-structure.md index a871b17cb106..08fb602e2858 100644 --- a/aspnetcore/blazor/project-structure.md +++ b/aspnetcore/blazor/project-structure.md @@ -89,12 +89,10 @@ The Blazor Server template creates the initial files and directory structure for * `appsettings.json` and environmental app settings files: Provide [configuration settings](xref:blazor/fundamentals/configuration) for the app. -* `Program.cs`: The app's entry point that sets up the ASP.NET Core [host](xref:fundamentals/host/generic-host). - -* `Startup.cs`: Contains the app's startup logic. The `Startup` class defines two methods: +* `Program.cs`: The app's entry point that sets up the ASP.NET Core [host](xref:fundamentals/host/generic-host) and contains the app's startup logic, including service registrations and request processing pipeline configuration: - * `ConfigureServices`: Configures the app's [dependency injection (DI)](xref:fundamentals/dependency-injection) services. Services are added by calling , and the `WeatherForecastService` is added to the service container for use by the example `FetchData` component. - * `Configure`: Configures the app's request handling pipeline: + * Specifies the app's [dependency injection (DI)](xref:fundamentals/dependency-injection) services. Services are added by calling , and the `WeatherForecastService` is added to the service container for use by the example `FetchData` component. + * Configures the app's request handling pipeline: * is called to set up an endpoint for the real-time connection with the browser. The connection is created with [SignalR](xref:signalr/introduction), which is a framework for adding real-time web functionality to apps. * [`MapFallbackToPage("/_Host")`](xref:Microsoft.AspNetCore.Builder.RazorPagesEndpointRouteBuilderExtensions.MapFallbackToPage%2A) is called to set up the root page of the app (`Pages/_Host.cshtml`) and enable navigation. diff --git a/aspnetcore/blazor/samples/6.0/BlazorSample_Server/routing/Program.cs b/aspnetcore/blazor/samples/6.0/BlazorSample_Server/routing/Program.cs new file mode 100644 index 000000000000..80ea9be3e81b --- /dev/null +++ b/aspnetcore/blazor/samples/6.0/BlazorSample_Server/routing/Program.cs @@ -0,0 +1,4 @@ +app.UseRouting(); + +app.MapBlazorHub(); +app.MapFallbackToPage("/_Host"); diff --git a/aspnetcore/blazor/samples/6.0/BlazorSample_Server/routing/Startup.cs b/aspnetcore/blazor/samples/6.0/BlazorSample_Server/routing/Startup.cs deleted file mode 100644 index 3627ef4cc3c5..000000000000 --- a/aspnetcore/blazor/samples/6.0/BlazorSample_Server/routing/Startup.cs +++ /dev/null @@ -1,15 +0,0 @@ -using Microsoft.AspNetCore.Builder; - -public class Startup -{ - public void Configure(IApplicationBuilder app) - { - app.UseRouting(); - - app.UseEndpoints(endpoints => - { - endpoints.MapBlazorHub(); - endpoints.MapFallbackToPage("/_Host"); - }); - } -} diff --git a/aspnetcore/blazor/security/includes/azure-scope.md b/aspnetcore/blazor/security/includes/azure-scope.md index 3eca1ddd108b..d36a437e8a57 100644 --- a/aspnetcore/blazor/security/includes/azure-scope.md +++ b/aspnetcore/blazor/security/includes/azure-scope.md @@ -1,7 +1,7 @@ --- no-loc: [Home, Privacy, Kestrel, appsettings.json, "ASP.NET Core Identity", cookie, Cookie, Blazor, "Blazor Server", "Blazor WebAssembly", "Identity", "Let's Encrypt", Razor, SignalR] --- -When working with a server API registered with AAD and the app's AAD registration is in an tenant that relies on an [unverified publisher domain](/azure/active-directory/develop/howto-configure-publisher-domain), the App ID URI of your server API app isn't `api://{SERVER API APP CLIENT ID OR CUSTOM VALUE}` but instead is in the format `https://{TENANT}.onmicrosoft.com/{SERVER API APP CLIENT ID OR CUSTOM VALUE}`. If that's the case, the default access token scope in `Program.Main` (`Program.cs`) of the **`Client`** app appears similar to the following: +When working with a server API registered with AAD and the app's AAD registration is in an tenant that relies on an [unverified publisher domain](/azure/active-directory/develop/howto-configure-publisher-domain), the App ID URI of your server API app isn't `api://{SERVER API APP CLIENT ID OR CUSTOM VALUE}` but instead is in the format `https://{TENANT}.onmicrosoft.com/{SERVER API APP CLIENT ID OR CUSTOM VALUE}`. If that's the case, the default access token scope in `Program.cs` of the **`Client`** app appears similar to the following: ```csharp options.ProviderOptions.DefaultAccessTokenScopes @@ -25,7 +25,7 @@ In the preceding configuration, the end of the `Audience` value does **not** inc Example: -`Program.Main` (`Program.cs`) of the **`Client`** app: +In `Program.cs` of the **`Client`** app: ```csharp options.ProviderOptions.DefaultAccessTokenScopes diff --git a/aspnetcore/blazor/security/includes/usermanager-signinmanager.md b/aspnetcore/blazor/security/includes/usermanager-signinmanager.md index 3fbc559cf079..53d6854aec48 100644 --- a/aspnetcore/blazor/security/includes/usermanager-signinmanager.md +++ b/aspnetcore/blazor/security/includes/usermanager-signinmanager.md @@ -8,7 +8,18 @@ Set the user identifier claim type when a Server app requires: * or in an API endpoint. * details, such as the user's name, email address, or lockout end time. -In `Startup.ConfigureServices`: +In `Program.cs` for ASP.NET Core 6.0 or later: + +```csharp +using System.Security.Claims; + +... + +builder.Services.Configure(options => + options.ClaimsIdentity.UserIdClaimType = ClaimTypes.NameIdentifier); +``` + +In `Startup.ConfigureServices` for versions of ASP.NET Core earlier than 6.0: ```csharp using System.Security.Claims; diff --git a/aspnetcore/blazor/security/index.md b/aspnetcore/blazor/security/index.md index 84c0924e3749..72280f035f34 100644 --- a/aspnetcore/blazor/security/index.md +++ b/aspnetcore/blazor/security/index.md @@ -151,14 +151,14 @@ using Microsoft.AspNetCore.Components.Authorization; builder.Services.AddScoped(); ``` -In a Blazor Server app, the `CustomAuthStateProvider` service is registered in `Startup.ConfigureServices`: +In a Blazor Server app, the `CustomAuthStateProvider` service is registered in `Program.cs`: ```csharp using Microsoft.AspNetCore.Components.Authorization; ... -services.AddScoped(); +builder.Services.AddScoped(); ``` Using the `CustomAuthStateProvider` in the preceding example, all users are authenticated with the username `mrfibuli`. @@ -217,7 +217,7 @@ Set up the `Task<` ``` -In a Blazor WebAssembly App, add services for options and authorization to `Program.Main`: +In a Blazor WebAssembly App, add services for options and authorization to `Program.cs`: ```csharp builder.Services.AddOptions(); @@ -760,7 +760,7 @@ Set up the `Task<` ``` -In a Blazor WebAssembly App, add services for options and authorization to `Program.Main`: +In a Blazor WebAssembly App, add services for options and authorization to `Program.cs`: ```csharp builder.Services.AddOptions(); diff --git a/aspnetcore/blazor/security/server/additional-scenarios.md b/aspnetcore/blazor/security/server/additional-scenarios.md index cf00bc2b7db1..ce80582b2b8f 100644 --- a/aspnetcore/blazor/security/server/additional-scenarios.md +++ b/aspnetcore/blazor/security/server/additional-scenarios.md @@ -46,14 +46,14 @@ public class TokenProvider } ``` -In `Startup.ConfigureServices`, add services for: +In `Program.cs`, add services for: * `IHttpClientFactory` * `TokenProvider` ```csharp -services.AddHttpClient(); -services.AddScoped(); +builder.Services.AddHttpClient(); +builder.Services.AddScoped(); ``` Define a class to pass in the initial app state with the access and refresh tokens: @@ -143,10 +143,10 @@ public class WeatherForecastService ## Set the authentication scheme -For an app that uses more than one Authentication Middleware and thus has more than one authentication scheme, the scheme that Blazor uses can be explicitly set in the endpoint configuration of `Startup.Configure`. The following example sets the Azure Active Directory scheme: +For an app that uses more than one Authentication Middleware and thus has more than one authentication scheme, the scheme that Blazor uses can be explicitly set in the endpoint configuration of `Program.cs`. The following example sets the Azure Active Directory scheme: ```csharp -endpoints.MapBlazorHub().RequireAuthorization( +app.MapBlazorHub().RequireAuthorization( new AuthorizeAttribute { AuthenticationSchemes = AzureADDefaults.AuthenticationScheme diff --git a/aspnetcore/blazor/security/webassembly/additional-scenarios.md b/aspnetcore/blazor/security/webassembly/additional-scenarios.md index f6261a9d1cc9..2226aafe41bc 100644 --- a/aspnetcore/blazor/security/webassembly/additional-scenarios.md +++ b/aspnetcore/blazor/security/webassembly/additional-scenarios.md @@ -93,7 +93,7 @@ public class CustomAuthorizationMessageHandler : AuthorizationMessageHandler } ``` -In `Program.Main` (`Program.cs`), `CustomAuthorizationMessageHandler` is registered as a scoped service and is configured as the for outgoing instances made by a named : +In `Program.cs`, `CustomAuthorizationMessageHandler` is registered as a scoped service and is configured as the for outgoing instances made by a named : ```csharp builder.Services.AddScoped(); @@ -136,7 +136,7 @@ The configured is used to make authorized requ can be configured with authorized URLs, scopes, and a return URL using the method. configures the handler to authorize outbound HTTP requests using an access token. The access token is only attached if at least one of the authorized URLs is a base of the request URI (). If the request URI is a relative URI, it's combined with the . -In the following example, configures an in `Program.Main` (`Program.cs`): +In the following example, configures an in `Program.cs`: ```csharp using System.Net.Http; @@ -202,7 +202,7 @@ public class WeatherForecastClient The placeholder `{APP ASSEMBLY}` is the app's assembly name (for example, `using static BlazorSample.Data;`). -`Program.Main` (`Program.cs`): +In `Program.cs`: ```csharp using System.Net.Http; @@ -234,7 +234,7 @@ protected override async Task OnInitializedAsync() The handler can be further configured with for outbound HTTP requests. -`Program.Main` (`Program.cs`): +In `Program.cs`: ```csharp builder.Services.AddHttpClient( @@ -254,7 +254,7 @@ For a hosted Blazor solution based on the [Blazor WebAssembly project template]( If the Blazor WebAssembly app ordinarily uses a secure default , the app can also make unauthenticated or unauthorized web API requests by configuring a named : -`Program.Main` (`Program.cs`): +In `Program.cs`: ```csharp builder.Services.AddHttpClient("WebAPI.NoAuthenticationClient", @@ -296,7 +296,7 @@ An alternative approach to using the i Access tokens can be manually obtained by calling `IAccessTokenProvider.RequestAccessToken`. In the following example, an additional scope is required by an app for the default . The Microsoft Authentication Library (MSAL) example configures the scope with `MsalProviderOptions`: -`Program.Main` (`Program.cs`): +In `Program.cs`: ```csharp builder.Services.AddMsalAuthentication(options => @@ -581,7 +581,7 @@ The `Authentication` component (`Pages/Authentication.razor`) saves and restores } ``` -This example uses Azure Active Directory (AAD) for authentication. In `Program.Main` (`Program.cs`): +This example uses Azure Active Directory (AAD) for authentication. In `Program.cs`: * The `ApplicationAuthenticationState` is configured as the Microsoft Autentication Library (MSAL) `RemoteAuthenticationState` type. * The state container is registered in the service container. @@ -629,7 +629,7 @@ In the following example, all the paths are prefixed with `/security`. } ``` -`Program.Main` (`Program.cs`): +In `Program.cs`: ```csharp builder.Services.AddApiAuthorization(options => { @@ -809,60 +809,52 @@ Prerendering content that requires authentication and authorization isn't curren * Prerenders paths for which authorization isn't required. * Doesn't prerender paths for which authorization is required. -In the client (**`Client`**) app's `Program` class (`Program.cs`), factor common service registrations into a separate method (for example, `ConfigureCommonServices`). Common services are those that the developer registers for use by both the client and server (**`Server`**) apps. +For the client (**`Client`**) app's `Program.cs`, factor common service registrations into a separate method (for example, `ConfigureCommonServices`). Common services are those that the developer registers for use by both the client and server (**`Server`**) apps. + +``: ```csharp -public class Program +public static void ConfigureCommonServices(IServiceCollection services) { - public static async Task Main(string[] args) - { - var builder = WebAssemblyHostBuilder.CreateDefault(args); - builder.RootComponents.Add...; + services.Add...; +} +``` - // Services that only the client app uses - builder.Services.AddScoped( ... ); +`Program.cs`: - ConfigureCommonServices(builder.Services); +```csharp +var builder = WebAssemblyHostBuilder.CreateDefault(args); +... - await builder.Build().RunAsync(); - } +builder.Services.AddScoped( ... ); - public static void ConfigureCommonServices(IServiceCollection services) - { - // Common service registrations that both apps use - services.Add...; - } -} +ConfigureCommonServices(builder.Services); + +await builder.Build().RunAsync(); ``` -In the server app's `Startup.ConfigureServices`, register the following additional services and call `ConfigureCommonServices`: +In the server app's `Program.cs` file, register the following additional services and call `ConfigureCommonServices`: ```csharp using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.Components.Server; using Microsoft.AspNetCore.Components.WebAssembly.Authentication; -public void ConfigureServices(IServiceCollection services) -{ - ... +... - services.AddRazorPages(); - services.AddScoped(); - services.AddScoped(); +builder.Services.AddRazorPages(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); - Client.Program.ConfigureCommonServices(services); -} +Client.Program.ConfigureCommonServices(services); ``` -In the server app's `Startup.Configure` method, replace [`endpoints.MapFallbackToFile("index.html")`](xref:Microsoft.AspNetCore.Builder.StaticFilesEndpointRouteBuilderExtensions.MapFallbackToFile%2A) with [`endpoints.MapFallbackToPage("/_Host")`](xref:Microsoft.AspNetCore.Builder.RazorPagesEndpointRouteBuilderExtensions.MapFallbackToPage%2A): +In the server app's `Program.cs`, replace [`app.MapFallbackToFile("index.html")`](xref:Microsoft.AspNetCore.Builder.StaticFilesEndpointRouteBuilderExtensions.MapFallbackToFile%2A) with [`app.MapFallbackToPage("/_Host")`](xref:Microsoft.AspNetCore.Builder.RazorPagesEndpointRouteBuilderExtensions.MapFallbackToPage%2A): ```csharp -app.UseEndpoints(endpoints => -{ - endpoints.MapControllers(); - endpoints.MapFallbackToPage("/_Host"); -}); +app.MapControllers(); +app.MapFallbackToPage("/_Host"); ``` In the server app, create a `Pages` folder if it doesn't exist. Create a `_Host.cshtml` page inside the server app's `Pages` folder. Paste the contents from the client app's `wwwroot/index.html` file into the `Pages/_Host.cshtml` file. Update the file's contents: @@ -963,7 +955,7 @@ The list of claims in the ID token changes for v2.0 endpoints. For more informat To configure a Blazor WebAssembly app to use the [ASP.NET Core gRPC framework](xref:grpc/index): * Enable gRPC-Web on the server. For more information, see . -* Register gRPC services for the app's message handler. The following example configures the app's authorization message handler to use the [`GreeterClient` service from the gRPC tutorial](xref:tutorials/grpc/grpc-start#create-a-grpc-service) (`Program.Main`): +* Register gRPC services for the app's message handler. The following example configures the app's authorization message handler to use the [`GreeterClient` service from the gRPC tutorial](xref:tutorials/grpc/grpc-start#create-a-grpc-service) (`Program.cs`): ```csharp using System.Net.Http; @@ -1038,9 +1030,9 @@ For more information, see . If an app requires a custom version of the [Microsoft Authentication Library for JavaScript (MSAL.js)](https://www.npmjs.com/package/@azure/msal-browser), perform the following steps: -1. Confirm the the system has the latest developer .NET SDK or obtain and install the latest developer SDK from [.NET Core SDK: Installers and Binaries](https://github.com/dotnet/installer#installers-and-binaries). Configuration of internal NuGet feeds isn't required for this scenario. +1. Confirm the system has the latest developer .NET SDK or obtain and install the latest developer SDK from [.NET Core SDK: Installers and Binaries](https://github.com/dotnet/installer#installers-and-binaries). Configuration of internal NuGet feeds isn't required for this scenario. 1. Set up the `dotnet/aspnetcore` GitHub repository for development per the docs at [Build ASP.NET Core from Source](https://github.com/dotnet/aspnetcore/blob/main/docs/BuildFromSource.md). Fork and clone or download a ZIP archive of the [dotnet/aspnetcore GitHub repository](https://github.com/dotnet/aspnetcore). -1. Open the the `src/Components/WebAssembly/Authentication.Msal/src/Interop/package.json` file and set the desired version of `@azure/msal-browser`. For a list of released versions, visit the [`@azure/msal-browser` npm website](https://www.npmjs.com/package/@azure/msal-browser) and select the **Versions** tab. +1. Open the `src/Components/WebAssembly/Authentication.Msal/src/Interop/package.json` file and set the desired version of `@azure/msal-browser`. For a list of released versions, visit the [`@azure/msal-browser` npm website](https://www.npmjs.com/package/@azure/msal-browser) and select the **Versions** tab. 1. Build the `Authentication.Msal` project in the `src/Components/WebAssembly/Authentication.Msal/src` folder with the `yarn build` command in a command shell. 1. If the app uses [compressed assets (Brotli/Gzip)](xref:blazor/host-and-deploy/webassembly#compression), compress the `Interop/dist/Release/AuthenticationService.js` file. 1. Copy the `AuthenticationService.js` file and compressed versions (`.br`/`.gz`) of the file, if produced, from the `Interop/dist/Release` folder into the app's `publish/wwwroot/_content/Microsoft.Authentication.WebAssembly.Msal` folder in the app's published assets. @@ -1134,7 +1126,7 @@ public class CustomAuthorizationMessageHandler : AuthorizationMessageHandler } ``` -In `Program.Main` (`Program.cs`), `CustomAuthorizationMessageHandler` is registered as a scoped service and is configured as the for outgoing instances made by a named : +In `Program.cs`, `CustomAuthorizationMessageHandler` is registered as a scoped service and is configured as the for outgoing instances made by a named : ```csharp builder.Services.AddScoped(); @@ -1177,7 +1169,7 @@ The configured is used to make authorized requ can be configured with authorized URLs, scopes, and a return URL using the method. configures the handler to authorize outbound HTTP requests using an access token. The access token is only attached if at least one of the authorized URLs is a base of the request URI (). If the request URI is a relative URI, it's combined with the . -In the following example, configures an in `Program.Main` (`Program.cs`): +In the following example, configures an in `Program.cs`: ```csharp using System.Net.Http; @@ -1243,7 +1235,7 @@ public class WeatherForecastClient The placeholder `{APP ASSEMBLY}` is the app's assembly name (for example, `using static BlazorSample.Data;`). -`Program.Main` (`Program.cs`): +In `Program.cs`: ```csharp using System.Net.Http; @@ -1275,7 +1267,7 @@ protected override async Task OnInitializedAsync() The handler can be further configured with for outbound HTTP requests. -`Program.Main` (`Program.cs`): +In `Program.cs`: ```csharp builder.Services.AddHttpClient( @@ -1295,7 +1287,7 @@ For a hosted Blazor solution based on the [Blazor WebAssembly project template]( If the Blazor WebAssembly app ordinarily uses a secure default , the app can also make unauthenticated or unauthorized web API requests by configuring a named : -`Program.Main` (`Program.cs`): +In `Program.cs`: ```csharp builder.Services.AddHttpClient("WebAPI.NoAuthenticationClient", @@ -1337,7 +1329,7 @@ An alternative approach to using the i Access tokens can be manually obtained by calling `IAccessTokenProvider.RequestAccessToken`. In the following example, an additional scope is required by an app for the default . The Microsoft Authentication Library (MSAL) example configures the scope with `MsalProviderOptions`: -`Program.Main` (`Program.cs`): +In `Program.cs`: ```csharp builder.Services.AddMsalAuthentication(options => @@ -1622,7 +1614,7 @@ The `Authentication` component (`Pages/Authentication.razor`) saves and restores } ``` -This example uses Azure Active Directory (AAD) for authentication. In `Program.Main` (`Program.cs`): +This example uses Azure Active Directory (AAD) for authentication. In `Program.cs`: * The `ApplicationAuthenticationState` is configured as the Microsoft Autentication Library (MSAL) `RemoteAuthenticationState` type. * The state container is registered in the service container. @@ -1670,7 +1662,7 @@ In the following example, all the paths are prefixed with `/security`. } ``` -`Program.Main` (`Program.cs`): +In `Program.cs`: ```csharp builder.Services.AddApiAuthorization(options => { @@ -2004,7 +1996,7 @@ The list of claims in the ID token changes for v2.0 endpoints. For more informat To configure a Blazor WebAssembly app to use the [ASP.NET Core gRPC framework](xref:grpc/index): * Enable gRPC-Web on the server. For more information, see . -* Register gRPC services for the app's message handler. The following example configures the app's authorization message handler to use the [`GreeterClient` service from the gRPC tutorial](xref:tutorials/grpc/grpc-start#create-a-grpc-service) (`Program.Main`): +* Register gRPC services for the app's message handler. The following example configures the app's authorization message handler to use the [`GreeterClient` service from the gRPC tutorial](xref:tutorials/grpc/grpc-start#create-a-grpc-service) (`Program.cs`): ```csharp using System.Net.Http; @@ -2079,9 +2071,9 @@ For more information, see . If an app requires a custom version of the [Microsoft Authentication Library for JavaScript (MSAL.js)](https://www.npmjs.com/package/@azure/msal-browser), perform the following steps: -1. Confirm the the system has the latest developer .NET SDK or obtain and install the latest developer SDK from [.NET Core SDK: Installers and Binaries](https://github.com/dotnet/installer#installers-and-binaries). Configuration of internal NuGet feeds isn't required for this scenario. +1. Confirm the system has the latest developer .NET SDK or obtain and install the latest developer SDK from [.NET Core SDK: Installers and Binaries](https://github.com/dotnet/installer#installers-and-binaries). Configuration of internal NuGet feeds isn't required for this scenario. 1. Set up the `dotnet/aspnetcore` GitHub repository for development per the docs at [Build ASP.NET Core from Source](https://github.com/dotnet/aspnetcore/blob/main/docs/BuildFromSource.md). Fork and clone or download a ZIP archive of the [dotnet/aspnetcore GitHub repository](https://github.com/dotnet/aspnetcore). -1. Open the the `src/Components/WebAssembly/Authentication.Msal/src/Interop/package.json` file and set the desired version of `@azure/msal-browser`. For a list of released versions, visit the [`@azure/msal-browser` npm website](https://www.npmjs.com/package/@azure/msal-browser) and select the **Versions** tab. +1. Open the `src/Components/WebAssembly/Authentication.Msal/src/Interop/package.json` file and set the desired version of `@azure/msal-browser`. For a list of released versions, visit the [`@azure/msal-browser` npm website](https://www.npmjs.com/package/@azure/msal-browser) and select the **Versions** tab. 1. Build the `Authentication.Msal` project in the `src/Components/WebAssembly/Authentication.Msal/src` folder with the `yarn build` command in a command shell. 1. If the app uses [compressed assets (Brotli/Gzip)](xref:blazor/host-and-deploy/webassembly#compression), compress the `Interop/dist/Release/AuthenticationService.js` file. 1. Copy the `AuthenticationService.js` file and compressed versions (`.br`/`.gz`) of the file, if produced, from the `Interop/dist/Release` folder into the app's `publish/wwwroot/_content/Microsoft.Authentication.WebAssembly.Msal` folder in the app's published assets. @@ -2175,7 +2167,7 @@ public class CustomAuthorizationMessageHandler : AuthorizationMessageHandler } ``` -In `Program.Main` (`Program.cs`), `CustomAuthorizationMessageHandler` is registered as a scoped service and is configured as the for outgoing instances made by a named : +In `Program.cs`, `CustomAuthorizationMessageHandler` is registered as a scoped service and is configured as the for outgoing instances made by a named : ```csharp builder.Services.AddScoped(); @@ -2218,7 +2210,7 @@ The configured is used to make authorized requ can be configured with authorized URLs, scopes, and a return URL using the method. configures the handler to authorize outbound HTTP requests using an access token. The access token is only attached if at least one of the authorized URLs is a base of the request URI (). If the request URI is a relative URI, it's combined with the . -In the following example, configures an in `Program.Main` (`Program.cs`): +In the following example, configures an in `Program.cs`: ```csharp using System.Net.Http; @@ -2284,7 +2276,7 @@ public class WeatherForecastClient The placeholder `{APP ASSEMBLY}` is the app's assembly name (for example, `using static BlazorSample.Data;`). -`Program.Main` (`Program.cs`): +In `Program.cs`: ```csharp using System.Net.Http; @@ -2316,7 +2308,7 @@ protected override async Task OnInitializedAsync() The handler can be further configured with for outbound HTTP requests. -`Program.Main` (`Program.cs`): +In `Program.cs`: ```csharp builder.Services.AddHttpClient( @@ -2336,7 +2328,7 @@ For a hosted Blazor solution based on the [Blazor WebAssembly project template]( If the Blazor WebAssembly app ordinarily uses a secure default , the app can also make unauthenticated or unauthorized web API requests by configuring a named : -`Program.Main` (`Program.cs`): +In `Program.cs`: ```csharp builder.Services.AddHttpClient("WebAPI.NoAuthenticationClient", @@ -2378,7 +2370,7 @@ An alternative approach to using the i Access tokens can be manually obtained by calling `IAccessTokenProvider.RequestAccessToken`. In the following example, an additional scope is required by an app for the default . The Microsoft Authentication Library (MSAL) example configures the scope with `MsalProviderOptions`: -`Program.Main` (`Program.cs`): +In `Program.cs`: ```csharp builder.Services.AddMsalAuthentication(options => @@ -2663,7 +2655,7 @@ The `Authentication` component (`Pages/Authentication.razor`) saves and restores } ``` -This example uses Azure Active Directory (AAD) for authentication. In `Program.Main` (`Program.cs`): +This example uses Azure Active Directory (AAD) for authentication. In `Program.cs`: * The `ApplicationAuthenticationState` is configured as the Microsoft Autentication Library (MSAL) `RemoteAuthenticationState` type. * The state container is registered in the service container. @@ -2711,7 +2703,7 @@ In the following example, all the paths are prefixed with `/security`. } ``` -`Program.Main` (`Program.cs`): +In `Program.cs`: ```csharp builder.Services.AddApiAuthorization(options => { @@ -3045,7 +3037,7 @@ The list of claims in the ID token changes for v2.0 endpoints. For more informat To configure a Blazor WebAssembly app to use the [ASP.NET Core gRPC framework](xref:grpc/index): * Enable gRPC-Web on the server. For more information, see . -* Register gRPC services for the app's message handler. The following example configures the app's authorization message handler to use the [`GreeterClient` service from the gRPC tutorial](xref:tutorials/grpc/grpc-start#create-a-grpc-service) (`Program.Main`): +* Register gRPC services for the app's message handler. The following example configures the app's authorization message handler to use the [`GreeterClient` service from the gRPC tutorial](xref:tutorials/grpc/grpc-start#create-a-grpc-service) (`Program.cs`): ```csharp using System.Net.Http; @@ -3120,9 +3112,9 @@ For more information, see . If an app requires a custom version of the [Microsoft Authentication Library for JavaScript (MSAL.js)](https://www.npmjs.com/package/@azure/msal-browser), perform the following steps: -1. Confirm the the system has the latest developer .NET SDK or obtain and install the latest developer SDK from [.NET Core SDK: Installers and Binaries](https://github.com/dotnet/installer#installers-and-binaries). Configuration of internal NuGet feeds isn't required for this scenario. +1. Confirm the system has the latest developer .NET SDK or obtain and install the latest developer SDK from [.NET Core SDK: Installers and Binaries](https://github.com/dotnet/installer#installers-and-binaries). Configuration of internal NuGet feeds isn't required for this scenario. 1. Set up the `dotnet/aspnetcore` GitHub repository for development per the docs at [Build ASP.NET Core from Source](https://github.com/dotnet/aspnetcore/blob/main/docs/BuildFromSource.md). Fork and clone or download a ZIP archive of the [dotnet/aspnetcore GitHub repository](https://github.com/dotnet/aspnetcore). -1. Open the the `src/Components/WebAssembly/Authentication.Msal/src/Interop/package.json` file and set the desired version of `@azure/msal-browser`. For a list of released versions, visit the [`@azure/msal-browser` npm website](https://www.npmjs.com/package/@azure/msal-browser) and select the **Versions** tab. +1. Open the `src/Components/WebAssembly/Authentication.Msal/src/Interop/package.json` file and set the desired version of `@azure/msal-browser`. For a list of released versions, visit the [`@azure/msal-browser` npm website](https://www.npmjs.com/package/@azure/msal-browser) and select the **Versions** tab. 1. Build the `Authentication.Msal` project in the `src/Components/WebAssembly/Authentication.Msal/src` folder with the `yarn build` command in a command shell. 1. If the app uses [compressed assets (Brotli/Gzip)](xref:blazor/host-and-deploy/webassembly#compression), compress the `Interop/dist/Release/AuthenticationService.js` file. 1. Copy the `AuthenticationService.js` file and compressed versions (`.br`/`.gz`) of the file, if produced, from the `Interop/dist/Release` folder into the app's `publish/wwwroot/_content/Microsoft.Authentication.WebAssembly.Msal` folder in the app's published assets. diff --git a/aspnetcore/blazor/security/webassembly/azure-active-directory-groups-and-roles.md b/aspnetcore/blazor/security/webassembly/azure-active-directory-groups-and-roles.md index 46e8d4fe24c5..3c3a4ba08ec9 100644 --- a/aspnetcore/blazor/security/webassembly/azure-active-directory-groups-and-roles.md +++ b/aspnetcore/blazor/security/webassembly/azure-active-directory-groups-and-roles.md @@ -47,7 +47,7 @@ These scopes are required in addition to the scopes required in AAD deployment s ## Group Membership Claims attribute -In the app's manifest in the the Azure portal for **CLIENT** and **SERVER** apps, set the [`groupMembershipClaims` attribute](/azure/active-directory/develop/reference-app-manifest#groupmembershipclaims-attribute) to `All`. A value of `All` results in obtaining all of the security groups, distribution groups, and roles that the signed-in user is a member of. +In the app's manifest in the Azure portal for **CLIENT** and **SERVER** apps, set the [`groupMembershipClaims` attribute](/azure/active-directory/develop/reference-app-manifest#groupmembershipclaims-attribute) to `All`. A value of `All` results in obtaining all of the security groups, distribution groups, and roles that the signed-in user is a member of. 1. Open the app's Azure portal registration. 1. Select **Manage** > **Manifest** in the sidebar. @@ -206,7 +206,7 @@ The preceding code doesn't include transitive memberships. If the app requires d The preceding code ignores group membership claims (`groups`) that are AAD Administrator Roles (`#microsoft.graph.directoryRole` type) because the GUID values returned by the Microsoft Identity Platform 2.0 are AAD Administrator Role **entity IDs** and not [**Role Template IDs**](/azure/active-directory/roles/permissions-reference#role-template-ids). Entity IDs aren't stable across tenants in Microsoft Identity Platform 2.0 and shouldn't be used to create authorization policies for users in apps. Always use **Role Template IDs** for AAD Administrator Roles **provided by `wids` claims**. -In `Program.Main` of the **CLIENT** app, configure the MSAL authentication to use the custom user account factory. +In `Program.cs` of the **CLIENT** app, configure the MSAL authentication to use the custom user account factory. `Program.cs`: @@ -231,7 +231,7 @@ builder.Services.AddGraphClient(); ## Authorization configuration -In the **CLIENT** app, create a [policy](xref:security/authorization/policies) for each [App Role](#app-roles), AAD Administrator Role, or security group in `Program.Main`. The following example creates a policy for the AAD *Billing Administrator* role: +In the **CLIENT** app, create a [policy](xref:security/authorization/policies) for each [App Role](#app-roles), AAD Administrator Role, or security group in `Program.cs`. The following example creates a policy for the AAD *Billing Administrator* role: ```csharp builder.Services.AddAuthorizationCore(options => @@ -317,10 +317,10 @@ A policy check can also be [performed in code with procedural logic](xref:blazor ## Authorize server API/web API access -A **SERVER** API app can authorize users to access secure API endpoints with [authorization policies](xref:security/authorization/policies) for security groups, AAD Administrator Roles, and App Roles when an access token contains `groups`, `wids`, and `http://schemas.microsoft.com/ws/2008/06/identity/claims/role` claims. The following example creates a policy for the AAD *Billing Administrator* role in `Startup.ConfigureServices` using the `wids` (well-known IDs/Role Template IDs) claims: +A **SERVER** API app can authorize users to access secure API endpoints with [authorization policies](xref:security/authorization/policies) for security groups, AAD Administrator Roles, and App Roles when an access token contains `groups`, `wids`, and `http://schemas.microsoft.com/ws/2008/06/identity/claims/role` claims. The following example creates a policy for the AAD *Billing Administrator* role in `Program.cs` using the `wids` (well-known IDs/Role Template IDs) claims: ```csharp -services.AddAuthorization(options => +builder.Services.AddAuthorization(options => { options.AddPolicy("BillingAdministrator", policy => policy.RequireClaim("wids", "b0f54661-2d74-4c50-afa3-1ec803f12efe")); @@ -367,7 +367,7 @@ The following example assumes that the **CLIENT** and **SERVER** apps are config The `CustomAccountFactory` shown in the [Custom user account](#custom-user-account) section is set up to act on a `roles` claim with a JSON array value. Add and register the `CustomAccountFactory` in the **CLIENT** app as shown in the [Custom user account](#custom-user-account) section. There's no need to provide code to remove the original `roles` claim because it's automatically removed by the framework. -In `Program.Main` of a **CLIENT** app, specify the claim named "`appRole`" as the role claim for checks: +In `Program.cs` of a **CLIENT** app, specify the claim named "`appRole`" as the role claim for checks: ```csharp builder.Services.AddMsalAuthentication(options => @@ -381,10 +381,10 @@ builder.Services.AddMsalAuthentication(options => > [!NOTE] > If you prefer to use the `directoryRoles` claim (ADD Administrator Roles), assign "`directoryRoles`" to the . -In `Startup.ConfigureServices` of a **SERVER** app, specify the claim named "`http://schemas.microsoft.com/ws/2008/06/identity/claims/role`" as the role claim for checks: +In `Program.cs` of a **SERVER** app, specify the claim named "`http://schemas.microsoft.com/ws/2008/06/identity/claims/role`" as the role claim for checks: ```csharp -services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) +builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApi(options => { Configuration.Bind("AzureAd", options); @@ -589,7 +589,7 @@ These scopes are required in addition to the scopes required in AAD deployment s ## Group Membership Claims attribute -In the app's manifest in the the Azure portal for **CLIENT** and **SERVER** apps, set the [`groupMembershipClaims` attribute](/azure/active-directory/develop/reference-app-manifest#groupmembershipclaims-attribute) to `All`. A value of `All` results in obtaining all of the security groups, distribution groups, and roles that the signed-in user is a member of. +In the app's manifest in the Azure portal for **CLIENT** and **SERVER** apps, set the [`groupMembershipClaims` attribute](/azure/active-directory/develop/reference-app-manifest#groupmembershipclaims-attribute) to `All`. A value of `All` results in obtaining all of the security groups, distribution groups, and roles that the signed-in user is a member of. 1. Open the app's Azure portal registration. 1. Select **Manage** > **Manifest** in the sidebar. @@ -748,7 +748,7 @@ The preceding code doesn't include transitive memberships. If the app requires d The preceding code ignores group membership claims (`groups`) that are AAD Administrator Roles (`#microsoft.graph.directoryRole` type) because the GUID values returned by the Microsoft Identity Platform 2.0 are AAD Administrator Role **entity IDs** and not [**Role Template IDs**](/azure/active-directory/roles/permissions-reference#role-template-ids). Entity IDs aren't stable across tenants in Microsoft Identity Platform 2.0 and shouldn't be used to create authorization policies for users in apps. Always use **Role Template IDs** for AAD Administrator Roles **provided by `wids` claims**. -In `Program.Main` of the **CLIENT** app, configure the MSAL authentication to use the custom user account factory. +In `Program.cs` of the **CLIENT** app, configure the MSAL authentication to use the custom user account factory. `Program.cs`: @@ -773,7 +773,7 @@ builder.Services.AddGraphClient(); ## Authorization configuration -In the **CLIENT** app, create a [policy](xref:security/authorization/policies) for each [App Role](#app-roles), AAD Administrator Role, or security group in `Program.Main`. The following example creates a policy for the AAD *Billing Administrator* role: +In the **CLIENT** app, create a [policy](xref:security/authorization/policies) for each [App Role](#app-roles), AAD Administrator Role, or security group in `Program.cs`. The following example creates a policy for the AAD *Billing Administrator* role: ```csharp builder.Services.AddAuthorizationCore(options => @@ -909,7 +909,7 @@ The following example assumes that the **CLIENT** and **SERVER** apps are config The `CustomAccountFactory` shown in the [Custom user account](#custom-user-account) section is set up to act on a `roles` claim with a JSON array value. Add and register the `CustomAccountFactory` in the **CLIENT** app as shown in the [Custom user account](#custom-user-account) section. There's no need to provide code to remove the original `roles` claim because it's automatically removed by the framework. -In `Program.Main` of a **CLIENT** app, specify the claim named "`appRole`" as the role claim for checks: +In `Program.cs` of a **CLIENT** app, specify the claim named "`appRole`" as the role claim for checks: ```csharp builder.Services.AddMsalAuthentication(options => diff --git a/aspnetcore/blazor/security/webassembly/graph-api.md b/aspnetcore/blazor/security/webassembly/graph-api.md index 12896ba170da..c3029865acec 100644 --- a/aspnetcore/blazor/security/webassembly/graph-api.md +++ b/aspnetcore/blazor/security/webassembly/graph-api.md @@ -137,7 +137,7 @@ The scope placeholders `"{SCOPE 1}", "{SCOPE 2}", ... "{SCOPE X}"` in the preced Scopes = new[] { "https://graph.microsoft.com/User.Read" } ``` -In `Program.Main` (`Program.cs`), add the Graph client services and configuration with the `AddGraphClient` extension method: +In `Program.cs`, add the Graph client services and configuration with the `AddGraphClient` extension method: ```csharp builder.Services.AddGraphClient("{SCOPE 1}", "{SCOPE 2}", ... "{SCOPE X}"); @@ -250,7 +250,7 @@ public class CustomAccountFactory } ``` -In `Program.Main` (`Program.cs`), configure the MSAL authentication to use the custom user account factory: If the app uses a custom user account class that extends , swap the custom user account class for in the following code: +In `Program.cs`, configure the MSAL authentication to use the custom user account factory: If the app uses a custom user account class that extends , swap the custom user account class for in the following code: ```csharp using Microsoft.AspNetCore.Components.WebAssembly.Authentication; @@ -300,7 +300,7 @@ public class GraphAPIAuthorizationMessageHandler : AuthorizationMessageHandler } ``` -In `Program.Main` (`Program.cs`), configure the named for Graph API: +In `Program.cs`, configure the named for Graph API: ```csharp builder.Services.AddScoped(); @@ -312,7 +312,7 @@ builder.Services.AddHttpClient("GraphAPI", ### Call Graph API from a component -This section uses the [Graph Authorization Message Handler (`GraphAuthorizationMessageHandler.cs`) and `Program.Main` additions to the app](#named-client-with-graph-api) described earlier in this article, which provides a named for Graph API. +This section uses the [Graph Authorization Message Handler (`GraphAuthorizationMessageHandler.cs`) and `Program.cs` additions to the app](#named-client-with-graph-api) described earlier in this article, which provides a named for Graph API. In a Razor component: @@ -403,7 +403,7 @@ In a Razor component: ### Customize user claims with Graph API and a named client -This section uses the [Graph Authorization Message Handler (`GraphAuthorizationMessageHandler.cs`) and `Program.Main` additions to the app](#named-client-with-graph-api) described earlier in this article, which provides a named for Graph API. +This section uses the [Graph Authorization Message Handler (`GraphAuthorizationMessageHandler.cs`) and `Program.cs` additions to the app](#named-client-with-graph-api) described earlier in this article, which provides a named for Graph API. In the following example, the app creates a mobile phone number claim for the user from their AAD user profile's mobile phone number. The app must have the `User.Read` Graph API scope configured in AAD. @@ -481,7 +481,7 @@ public class CustomAccountFactory } ``` -In `Program.Main` (`Program.cs`), configure the MSAL authentication to use the custom user account factory: If the app uses a custom user account class that extends , swap the custom user account class for in the following code: +In `Program.cs`, configure the MSAL authentication to use the custom user account factory: If the app uses a custom user account class that extends , swap the custom user account class for in the following code: ```csharp using Microsoft.AspNetCore.Components.WebAssembly.Authentication; @@ -628,7 +628,7 @@ The scope placeholders `"{SCOPE 1}", "{SCOPE 2}", ... "{SCOPE X}"` in the preced Scopes = new[] { "https://graph.microsoft.com/User.Read" } ``` -In `Program.Main` (`Program.cs`), add the Graph client services and configuration with the `AddGraphClient` extension method: +In `Program.cs`, add the Graph client services and configuration with the `AddGraphClient` extension method: ```csharp builder.Services.AddGraphClient("{SCOPE 1}", "{SCOPE 2}", ... "{SCOPE X}"); @@ -741,7 +741,7 @@ public class CustomAccountFactory } ``` -In `Program.Main` (`Program.cs`), configure the MSAL authentication to use the custom user account factory: If the app uses a custom user account class that extends , swap the custom user account class for in the following code: +In `Program.cs`, configure the MSAL authentication to use the custom user account factory: If the app uses a custom user account class that extends , swap the custom user account class for in the following code: ```csharp using Microsoft.AspNetCore.Components.WebAssembly.Authentication; @@ -791,7 +791,7 @@ public class GraphAPIAuthorizationMessageHandler : AuthorizationMessageHandler } ``` -In `Program.Main` (`Program.cs`), configure the named for Graph API: +In `Program.cs`, configure the named for Graph API: ```csharp builder.Services.AddScoped(); @@ -803,7 +803,7 @@ builder.Services.AddHttpClient("GraphAPI", ### Call Graph API from a component -This section uses the [Graph Authorization Message Handler (`GraphAuthorizationMessageHandler.cs`) and `Program.Main` additions to the app](#named-client-with-graph-api) described earlier in this article, which provides a named for Graph API. +This section uses the [Graph Authorization Message Handler (`GraphAuthorizationMessageHandler.cs`) and `Program.cs` additions to the app](#named-client-with-graph-api) described earlier in this article, which provides a named for Graph API. In a Razor component: @@ -894,7 +894,7 @@ In a Razor component: ### Customize user claims with Graph API and a named client -This section uses the [Graph Authorization Message Handler (`GraphAuthorizationMessageHandler.cs`) and `Program.Main` additions to the app](#named-client-with-graph-api) described earlier in this article, which provides a named for Graph API. +This section uses the [Graph Authorization Message Handler (`GraphAuthorizationMessageHandler.cs`) and `Program.cs` additions to the app](#named-client-with-graph-api) described earlier in this article, which provides a named for Graph API. In the following example, the app creates a mobile phone number claim for the user from their AAD user profile's mobile phone number. The app must have the `User.Read` Graph API scope configured in AAD. @@ -972,7 +972,7 @@ public class CustomAccountFactory } ``` -In `Program.Main` (`Program.cs`), configure the MSAL authentication to use the custom user account factory: If the app uses a custom user account class that extends , swap the custom user account class for in the following code: +In `Program.cs`, configure the MSAL authentication to use the custom user account factory: If the app uses a custom user account class that extends , swap the custom user account class for in the following code: ```csharp using Microsoft.AspNetCore.Components.WebAssembly.Authentication; @@ -1027,7 +1027,7 @@ public class GraphAPIAuthorizationMessageHandler : AuthorizationMessageHandler } ``` -In `Program.Main` (`Program.cs`), configure the named for Graph API: +In `Program.cs`, configure the named for Graph API: ```csharp builder.Services.AddScoped(); @@ -1039,7 +1039,7 @@ builder.Services.AddHttpClient("GraphAPI", ### Call Graph API from a component -This section uses the [Graph Authorization Message Handler (`GraphAuthorizationMessageHandler.cs`) and `Program.Main` additions to the app](#named-client-with-graph-api) described earlier in this article, which provides a named for Graph API. +This section uses the [Graph Authorization Message Handler (`GraphAuthorizationMessageHandler.cs`) and `Program.cs` additions to the app](#named-client-with-graph-api) described earlier in this article, which provides a named for Graph API. In a Razor component: @@ -1130,7 +1130,7 @@ In a Razor component: ### Customize user claims with Graph API and a named client -This section uses the [Graph Authorization Message Handler (`GraphAuthorizationMessageHandler.cs`) and `Program.Main` additions to the app](#named-client-with-graph-api) described earlier in this article, which provides a named for Graph API. +This section uses the [Graph Authorization Message Handler (`GraphAuthorizationMessageHandler.cs`) and `Program.cs` additions to the app](#named-client-with-graph-api) described earlier in this article, which provides a named for Graph API. In the following example, the app creates a mobile phone number claim for the user from their AAD user profile's mobile phone number. The app must have the `User.Read` Graph API scope configured in AAD. @@ -1208,7 +1208,7 @@ public class CustomAccountFactory } ``` -In `Program.Main` (`Program.cs`), configure the MSAL authentication to use the custom user account factory: If the app uses a custom user account class that extends , swap the custom user account class for in the following code: +In `Program.cs`, configure the MSAL authentication to use the custom user account factory: If the app uses a custom user account class that extends , swap the custom user account class for in the following code: ```csharp using Microsoft.AspNetCore.Components.WebAssembly.Authentication; diff --git a/aspnetcore/blazor/security/webassembly/hosted-with-azure-active-directory-b2c.md b/aspnetcore/blazor/security/webassembly/hosted-with-azure-active-directory-b2c.md index 5f43a611d544..80741ef34baf 100644 --- a/aspnetcore/blazor/security/webassembly/hosted-with-azure-active-directory-b2c.md +++ b/aspnetcore/blazor/security/webassembly/hosted-with-azure-active-directory-b2c.md @@ -118,7 +118,7 @@ dotnet new blazorwasm -au IndividualB2C --aad-b2c-instance "{AAD B2C INSTANCE}" The output location specified with the `-o|--output` option creates a project folder if it doesn't exist and becomes part of the app's name. **Avoid using dashes (`-`) in the app name that break the formation of the OIDC app identifier (see the earlier WARNING).** > [!NOTE] -> The scope set up in a hosted Blazor WebAssembly solution by the [Blazor WebAssembly project template](xref:blazor/project-structure) might have the App ID URI host repeated. Confirm that the scope configured for the `DefaultAccessTokenScopes` collection is correct in `Program.Main` (`Program.cs`) of the **`Client`** app. +> The scope set up in a hosted Blazor WebAssembly solution by the [Blazor WebAssembly project template](xref:blazor/project-structure) might have the App ID URI host repeated. Confirm that the scope configured for the `DefaultAccessTokenScopes` collection is correct in `Program.cs` of the **`Client`** app. > [!NOTE] > In the Azure portal, the **`Client`** app's platform configuration **Redirect URI** is configured for port 5001 for apps that run on the Kestrel server with default settings. @@ -168,16 +168,16 @@ By default, the `User.Identity.Name` isn't populated. To configure the app to receive the value from the `name` claim type: -* Add a namespace for to `Startup.cs`: +* Add a namespace for to `Program.cs`: ```csharp using Microsoft.AspNetCore.Authentication.JwtBearer; ``` -* Configure the of the in `Startup.ConfigureServices`: +* Configure the of the in `Program.cs`: ```csharp - services.Configure( + builder.Services.Configure( JwtBearerDefaults.AuthenticationScheme, options => { options.TokenValidationParameters.NameClaimType = "name"; @@ -524,7 +524,7 @@ dotnet new blazorwasm -au IndividualB2C --aad-b2c-instance "{AAD B2C INSTANCE}" The output location specified with the `-o|--output` option creates a project folder if it doesn't exist and becomes part of the app's name. **Avoid using dashes (`-`) in the app name that break the formation of the OIDC app identifier (see the earlier WARNING).** > [!NOTE] -> The scope set up in a hosted Blazor WebAssembly solution by the [Blazor WebAssembly project template](xref:blazor/project-structure) might have the App ID URI host repeated. Confirm that the scope configured for the `DefaultAccessTokenScopes` collection is correct in `Program.Main` (`Program.cs`) of the **`Client`** app. +> The scope set up in a hosted Blazor WebAssembly solution by the [Blazor WebAssembly project template](xref:blazor/project-structure) might have the App ID URI host repeated. Confirm that the scope configured for the `DefaultAccessTokenScopes` collection is correct in `Program.cs` of the **`Client`** app. > [!NOTE] > In the Azure portal, the **`Client`** app's platform configuration **Redirect URI** is configured for port 5001 for apps that run on the Kestrel server with default settings. @@ -930,7 +930,7 @@ dotnet new blazorwasm -au IndividualB2C --aad-b2c-instance "{AAD B2C INSTANCE}" The output location specified with the `-o|--output` option creates a project folder if it doesn't exist and becomes part of the app's name. **Avoid using dashes (`-`) in the app name that break the formation of the OIDC app identifier (see the earlier WARNING).** > [!NOTE] -> The scope set up in a hosted Blazor WebAssembly solution by the [Blazor WebAssembly project template](xref:blazor/project-structure) might have the App ID URI host repeated. Confirm that the scope configured for the `DefaultAccessTokenScopes` collection is correct in `Program.Main` (`Program.cs`) of the **`Client`** app. +> The scope set up in a hosted Blazor WebAssembly solution by the [Blazor WebAssembly project template](xref:blazor/project-structure) might have the App ID URI host repeated. Confirm that the scope configured for the `DefaultAccessTokenScopes` collection is correct in `Program.cs` of the **`Client`** app. > [!NOTE] > In the Azure portal, the **`Client`** app's platform configuration **Redirect URI** is configured for port 5001 for apps that run on the Kestrel server with default settings. diff --git a/aspnetcore/blazor/security/webassembly/hosted-with-azure-active-directory.md b/aspnetcore/blazor/security/webassembly/hosted-with-azure-active-directory.md index ad9a79a6cdf2..0df99387f99a 100644 --- a/aspnetcore/blazor/security/webassembly/hosted-with-azure-active-directory.md +++ b/aspnetcore/blazor/security/webassembly/hosted-with-azure-active-directory.md @@ -164,16 +164,16 @@ By default, the **`Server`** app API populates `User.Identity.Name` with the val To configure the app to receive the value from the `name` claim type: -* Add a namespace for to `Startup.cs`: +* Add a namespace for to `Program.cs`: ```csharp using Microsoft.AspNetCore.Authentication.JwtBearer; ``` -* Configure the of the in `Startup.ConfigureServices`: +* Configure the of the in `Program.cs`: ```csharp - services.Configure( + builder.Services.Configure( JwtBearerDefaults.AuthenticationScheme, options => { options.TokenValidationParameters.NameClaimType = "name"; diff --git a/aspnetcore/blazor/security/webassembly/hosted-with-identity-server.md b/aspnetcore/blazor/security/webassembly/hosted-with-identity-server.md index 900b46880c40..4b90592ba712 100644 --- a/aspnetcore/blazor/security/webassembly/hosted-with-identity-server.md +++ b/aspnetcore/blazor/security/webassembly/hosted-with-identity-server.md @@ -74,16 +74,16 @@ The following sections describe additions to the project when authentication sup The `Startup` class has the following additions. -* In `Startup.ConfigureServices`: +* In `Program.cs`: * ASP.NET Core Identity: ```csharp - services.AddDbContext(options => + builder.Services.AddDbContext(options => options.UseSqlite( Configuration.GetConnectionString("DefaultConnection"))); - services.AddDefaultIdentity(options => + builder.Services.AddDefaultIdentity(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores(); ``` @@ -91,18 +91,18 @@ The `Startup` class has the following additions. * IdentityServer with an additional helper method that sets up default ASP.NET Core conventions on top of IdentityServer: ```csharp - services.AddIdentityServer() + builder.Services.AddIdentityServer() .AddApiAuthorization(); ``` * Authentication with an additional helper method that configures the app to validate JWT tokens produced by IdentityServer: ```csharp - services.AddAuthentication() + builder.Services.AddAuthentication() .AddIdentityServerJwt(); ``` -* In `Startup.Configure`: +* In `Program.cs`: * The IdentityServer middleware exposes the OpenID Connect (OIDC) endpoints: @@ -185,7 +185,7 @@ For the placeholder `{VERSION}`, the latest stable version of the package that m ### `HttpClient` configuration -In `Program.Main` (`Program.cs`), a named (`{APP ASSEMBLY}.ServerAPI`) is configured to supply instances that include access tokens when making requests to the server API: +In `Program.cs`, a named (`{APP ASSEMBLY}.ServerAPI`) is configured to supply instances that include access tokens when making requests to the server API: ```csharp builder.Services.AddHttpClient("{APP ASSEMBLY}.ServerAPI", @@ -348,7 +348,7 @@ public class CustomUserFactory } ``` -In the **`Client`** app, register the factory in `Program.Main` (`Program.cs`): +In the **`Client`** app, register the factory in `Program.cs`: ```csharp builder.Services.AddApiAuthorization() @@ -435,14 +435,14 @@ public class ProfileService : IProfileService } ``` -In the **`Server`** app, register the Profile Service in `Startup.ConfigureServices`: +In the **`Server`** app, register the Profile Service in `Program.cs`: ```csharp using Duende.IdentityServer.Services; ... -services.AddTransient(); +builder.Services.AddTransient(); JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("role"); ``` @@ -756,7 +756,7 @@ For the placeholder `{VERSION}`, the latest stable version of the package that m ### `HttpClient` configuration -In `Program.Main` (`Program.cs`), a named (`{APP ASSEMBLY}.ServerAPI`) is configured to supply instances that include access tokens when making requests to the server API: +In `Program.cs`, a named (`{APP ASSEMBLY}.ServerAPI`) is configured to supply instances that include access tokens when making requests to the server API: ```csharp builder.Services.AddHttpClient("{APP ASSEMBLY}.ServerAPI", @@ -919,7 +919,7 @@ public class CustomUserFactory } ``` -In the **`Client`** app, register the factory in `Program.Main` (`Program.cs`): +In the **`Client`** app, register the factory in `Program.cs`: ```csharp builder.Services.AddApiAuthorization() @@ -1497,7 +1497,7 @@ For the placeholder `{VERSION}`, the latest stable version of the package that m ### `HttpClient` configuration -In `Program.Main` (`Program.cs`), a named (`{APP ASSEMBLY}.ServerAPI`) is configured to supply instances that include access tokens when making requests to the server API: +In `Program.cs`, a named (`{APP ASSEMBLY}.ServerAPI`) is configured to supply instances that include access tokens when making requests to the server API: ```csharp builder.Services.AddHttpClient("{APP ASSEMBLY}.ServerAPI", @@ -1660,7 +1660,7 @@ public class CustomUserFactory } ``` -In the **`Client`** app, register the factory in `Program.Main` (`Program.cs`): +In the **`Client`** app, register the factory in `Program.cs`: ```csharp builder.Services.AddApiAuthorization() diff --git a/aspnetcore/blazor/webassembly-lazy-load-assemblies.md b/aspnetcore/blazor/webassembly-lazy-load-assemblies.md index f4552935b445..da6e7aff1975 100644 --- a/aspnetcore/blazor/webassembly-lazy-load-assemblies.md +++ b/aspnetcore/blazor/webassembly-lazy-load-assemblies.md @@ -171,16 +171,16 @@ To rectify this: The framework's lazy loading implementation supports lazy loading with prerendering in a hosted Blazor WebAssembly solution. During prerendering, all assemblies, including those marked for lazy loading, are assumed to be loaded. Manually register the service in the **`Server`** project. -At the top of the `Startup.cs` file of the **`Server`** project, add the namespace for : +At the top of the `Program.cs` file of the **`Server`** project, add the namespace for : ```csharp using Microsoft.AspNetCore.Components.WebAssembly.Services; ``` -In the `Startup.ConfigureServices` method (`Startup.cs`) of the **`Server`** project, register the service: +In `Program.cs` of the **`Server`** project, register the service: ```csharp -services.AddScoped(); +builder.Services.AddScoped(); ``` ## Complete example