Migrate an XAF ASP.NET Core Application to Minimal Hosting Model and Blazor Web App Template
- 13 minutes to read
XAF introduced changes to application templates in v26.2. ASP.NET Core Blazor, Middle Tier, and Web API Service templates now use the .NET minimal hosting model and Blazor Web App structure. This help topic lists template differences between this and previous versions, and explains how to migrate an existing project to the new structure.
Migration is optional: projects with the old structure (with Startup.cs) continue to work. Migrate your projects if you want their structure to match up-to-date Microsoft ASP.NET Core documentation.
The following instructions work with template code only. If your files contain additional code, move code changes to the same place in new files.
Tip
You can use this article to create a prompt that instructs LLM to update your application.
Always review AI-generated output: check for architectural problems, security vulnerabilities, and adherence to project standards. AI-generated output can vary based on factors such as the prompt, AI model, and project code clarity.
Affected Projects
- Blazor
- Middle Tier
- Web API Service
WinForms projects are not affected.
What Changed
| Old Template | New Template (v26.2+) |
|---|---|
Program.cs (including Main, CreateHostBuilder,IDesignTimeApplicationFactory) + Startup.cs |
Program.cs with top-level statements |
| Pages/_Host.cshtml | Components/App.razor |
| App.razor | Components/Routes.razor + Components/Pages/NotFound.razor |
| — | New files: Components/Layout/ReconnectModal.razor, Components/Layout/ReconnectModal.razor.css, Components/Layout/ReconnectModal.razor.js |
| _Imports.razor | _Imports.razor+ @using SolutionName.Blazor.Server.Components.Layout |
Prerequisites
- Upgrade your solution to v26.2 and .NET 10. Verify that the solution builds and runs successfully.
- Create a separate XAF v26.2 reference solution. Use the DevExpress Template Kit or .NET CLI. Configure the reference solution to match your existing project, including the solution name, target platforms, ORM, security settings, and Middle Tier or Web API Service options. During migration, compare your project files with the corresponding files in the reference solution, particularly Program.cs and files in the Components folder.
Step 1. Unify Startup.cs and Program.cs in a Single Program.cs File
In the new project structure, Program.cs no longer contains a class declaration. Instead, it uses top-level statements to execute the application startup code in the following order:
- Code that
Program.Mainpreviously executed. - Service registrations that
Startup.ConfigureServicespreviously defined. - The request pipeline that
Startup.Configurepreviously defined.
Migrate Blazor Projects
When unifying Program.cs and Startup.cs, apply the following changes.
- Merge using directives
- Copy required
usingdirectives from existing Program.cs and Startup.cs files. - Add the following directives:
using SolutionName.Blazor.Server;using SolutionName.Blazor.Server.Components;using DevExpress.ExpressApp.Blazor;
- Copy required
- Update lambda parameters
- Rename all lambda parameters named
buildertoxafBuilder, including nested lambda expressions such asMultipleDatabases(builder => ...). Otherwise, the CS0136 compiler error occurs becausebuildernow refers toWebApplicationBuilder. - Update other Startup members
- If the
Startupconstructor accepts anIWebHostEnvironmentparameter, usebuilder.Environment. - Move helper methods to the end of Program.cs and declare them as local functions.
- If the
- Move the Request Pipeline
Move the body of the
Startup.Configuremethod to the new WebApplication setup, placing it after the--updateDatabasebranch. Apply the following changes:Update references to the environment and configuration.
The
appvariable is now aWebApplicationinstance, not a parameter of theConfiguremethod.- Replace
envwithapp.Environment. - Replace
Configurationwithapp.Configuration.
- Replace
Replace endpoint configuration with direct mapping calls.
Replace
app.UseEndpoints(endpoints => { ... })with direct calls toapp.MapXafEndpoints()andapp.MapControllers().Remove app.UseDeveloperExceptionPage().
WebApplicationautomatically adds the developer exception page in the Development environment.- If the Development branch contains other code, such as Swagger configuration, preserve that code in a separate
if (app.Environment.IsDevelopment())block.
Add status code page handling.
Add
UseStatusCodePagesWithReExecute("/not-found"). This middleware displays the NotFound.razor page when a URL cannot be found. In previous versions, the<NotFound>fragment in App.razor handled this behavior. Web API requests under/apiare unaffected and continue to return plain HTTP status codes.Replace static file middleware with static asset mapping.
Replace
app.UseStaticFiles()withapp.MapStaticAssets()and place it afterapp.UseXaf().Replace the Blazor Server endpoint configuration with Razor component mapping.
Replace
MapBlazorHub()andMapFallbackToPage("/_Host")withMapRazorComponents<App>()…. The XAF assembly provides the routes for XAF Views.- Ensure antiforgery middleware is registered in the correct order.
- If the project does not already call
UseAntiforgery(), add the call. - Place
app.UseAntiforgery()afterapp.UseAuthorization(). If that call is missing, your next choices areapp.UseAuthentication(), thenapp.UseRouting().
- If the project does not already call
- Delete unnecessary files
- After migrating the startup code, delete Startup.cs. If your project contains Startup.DevExpress.cs, delete that file as well. Older versions of DevExpress Blazor packages generated this additional file.
The following code snippet demonstrates the updated Program.cs file in a Blazor application. Code comments demonstrate where the code was and what it looked like before v26.2.
// up to v26.2: namespace SolutionName.Blazor.Server; (remove the declaration)
using DevExpress.ExpressApp.Blazor;
using SolutionName.Blazor.Server;
using SolutionName.Blazor.Server.Components;
// ...other using directives from Program.cs and Startup.cs
// up to v26.2: public static int Main(string[] args) { ... }
if(ContainsArgument(args, "help") || ContainsArgument(args, "h")) {
// ...the help text
return 0;
}
// up to v26.2: else { ... }
// ...other code from the Main method
// up to v26.2: IHost host = CreateHostBuilder(args).Build();
var builder = WebApplication.CreateBuilder(args);
// up to v26.2: Startup.ConfigureServices(IServiceCollection services) { ... }
// up to v26.2: services.AddRazorPages();
// services.AddServerSideBlazor();
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
// up to v26.2: services.AddXaf(Configuration, builder => {
builder.Services.AddXaf(builder.Configuration, xafBuilder => {
// up to v26.2: builder.UseApplication<SolutionNameBlazorApplication>();
xafBuilder.UseApplication<SolutionNameBlazorApplication>();
// ...
});
// ...the rest of the ConfigureServices body (services. -> builder.Services.)
WebApplication app = builder.Build();
if(ContainsArgument(args, "updateDatabase")) {
// up to v26.2: host.Services.CreateScope()
using(var serviceScope = app.Services.CreateScope()) {
return serviceScope.ServiceProvider.GetRequiredService<IDBUpdater>()
.Update(ContainsArgument(args, "forceUpdate"), ContainsArgument(args, "silent"));
}
}
// up to v26.2: Startup.Configure(IApplicationBuilder app, IWebHostEnvironment env) { ... }
// Moved Request Pipeline section
if(!app.Environment.IsDevelopment()) {
app.UseExceptionHandler("/Error", createScopeForErrors: true);
app.UseHsts();
}
app.UseWhen(context => !context.Request.Path.StartsWithSegments("/api"),
appBuilder => appBuilder.UseStatusCodePagesWithReExecute("/not-found",
createScopeForStatusCodePages: true));
app.UseHttpsRedirection();
app.UseRequestLocalization();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseAntiforgery();
app.UseXaf();
app.MapStaticAssets();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode()
.AddAdditionalAssemblies(typeof(BlazorApplication).Assembly);
app.MapXafEndpoints();
app.MapControllers();
app.Run();
return 0;
// up to v26.2: private static bool ContainsArgument(...) in the Program class
bool ContainsArgument(string[] args, string argument) {
return args.Any(arg => arg.TrimStart('/').TrimStart('-').ToLower() == argument.ToLower());
}
Migrate Middle Tier and Web API Service Projects
Middle Tier and Web API Service projects do not include a Razor UI, so merging the Program.cs and Startup.cs files differs slightly from the process used in Blazor projects.
- Merge using directives
- Copy required
usingdirectives from existing Program.cs and Startup.cs files only if Program.cs uses your classes from this namespace. - Add the following directive:
using SolutionName.Blazor.Server;
- Copy required
- Update lambda parameters
- In
AddXafMiddleTier(Configuration, builder => ...)andAddXafWebApi(builder => ...), renamebuildertoxafBuilder. - In
MultipleDatabases(builder => ...), renamebuildertomultiBuilderin Middle Tier projects and toxafBuilderin Web API Service projects.
- In
- Update other Startup members
- If the
Startupconstructor accepts anIWebHostEnvironmentparameter, usebuilder.Environment. - Move helper methods to the end of Program.cs and declare them as local functions.
- If the
- Move the Request Pipeline
Move the body of the
Startup.Configuremethod to the new WebApplication setup, placing it after the--updateDatabasebranch. Apply the following changes:Update references to the environment and configuration.
The
appvariable is now aWebApplicationinstance, not a parameter of theConfiguremethod.- Replace
envwithapp.Environment. - Replace
Configurationwithapp.Configuration.
- Replace
Replace endpoint configuration with direct mapping calls.
- Replace
app.UseEndpoints(endpoints => { ... })withapp.MapControllers(). - In Web API Service projects, also add
app.MapXafEndpoints().
- Replace
- Remove app.UseDeveloperExceptionPage().
WebApplicationautomatically adds the developer exception page in the Development environment.- In Web API Service projects, preserve Swagger calls in
if (app.Environment.IsDevelopment())block.
- Ensure antiforgery middleware is registered in the correct order.
- If the project does not already call
UseAntiforgery(), add the call. - Place
app.UseAntiforgery()afterapp.UseAuthorization(). If that call is missing, your next choices areapp.UseAuthentication(), thenapp.UseRouting().
- If the project does not already call
- Delete unnecessary files
- After migrating startup code, delete Startup.cs. If your project contains Startup.DevExpress.cs, delete that file as well. Older versions of DevExpress Blazor packages generated this additional file.
The following code snippets show the result:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddXafMiddleTier(builder.Configuration, xafBuilder => {
// ...
});
// ...the rest of the ConfigureServices body
WebApplication app = builder.Build();
// ...--updateDatabase branch (host.Services -> app.Services)
if(!app.Environment.IsDevelopment()) {
app.UseExceptionHandler("/Error");
app.UseHsts();
}
#if RELEASE
app.UseHttpsRedirection();
#endif
app.UseRequestLocalization();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseAntiforgery();
app.UseXafMiddleTier();
app.MapControllers();
app.Run();
return 0;
Step 2. Replace _Host.cshtml and App.razor in Blazor
In the old Blazor Server model, Pages/_Host.cshtml serves as the HTML page that hosts the root App component. In the new Blazor Web App model, the standard template no longer requires a separate _Host.cshtml file. Instead, the root App.razor component takes over its role.
- Copy the Components folder from the reference solution to the SolutionName.Blazor.Server project. If the reference solution uses a different project name, update the copied files to use your project’s name.
- Delete Pages/_Host.cshtml and the old App.razor file.
- Add the following namespace to _Imports.razor:
@using SolutionName.Blazor.Server.Components.Layout.
You do not need to move your existing Razor components and pages. The router discovers them in the project assembly.
The copied Components folder contains the following files:
| File | Purpose |
|---|---|
| App.razor | Replaces Pages/_Host.cshtml. |
| Routes.razor | Replaces the old App.razor. |
| Pages/NotFound.razor | Replaces the <NotFound> fragment of the old Router. |
| Layout/ReconnectModal.razor, Layout/ReconnectModal.razor.css, Layout/ReconnectModal.razor.js |
Handle reconnection UI. Copy these files without changes. |
Components/App.razor
In the old Blazor Server model, App.razor typically contains the <Router> component. In the new Blazor Web App template, these responsibilities are separated: App.razor serves as the HTML shell, while routing is handled by Routes.razor.
Important
XAF does not support prerendering. Do not use Blazor’s built-in InteractiveServer render mode. Instead, use the InteractiveServerWithoutPrerendering mode declared in the @code block of App.razor.
- The CSS isolation bundle name should follow this pattern:
<AssemblyName>.styles.css. Correct the bundle name to match this naming convention. - If your old Pages/_Host.cshtml file contains additional markup, such as meta tags, styles, or scripts, copy that markup to the corresponding location in App.razor.
- If your project was created using an older template, remove the obsolete script reference. Delete
<script src="_content/DevExpress.ExpressApp.Blazor/scripts.js">. - Add the
DxResourceManager.RegisterScripts()call, even if the old App.razor file does not contain it. Without this call, XAF scripts are not loaded, and the application remains stuck on the splash screen.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no" />
<meta name="mobile-web-app-capable" content="yes" />
<!-- meta name="theme-color" content="#000000" -->
<HeadOutlet />
<PageTitle>SolutionName</PageTitle>
<base href="/" />
<ImportMap />
<BootstrapThemeLink />
<link href="@Assets["_content/DevExpress.ExpressApp.Blazor/styles.css"]" rel="stylesheet" />
<link href="@Assets["css/site.css"]" rel="stylesheet" />
<link href="@Assets["SolutionName.Blazor.Server.styles.css"]" rel="stylesheet" />
@DxResourceManager.RegisterScripts()
</head>
<body>
<SplashScreen Caption="SolutionName" ImagePath="images/SplashScreen.svg" />
<app class="d-none">
<Routes @rendermode="InteractiveServerWithoutPrerendering" />
</app>
<AlertsHandler @rendermode="InteractiveServerWithoutPrerendering" />
<div id="blazor-error-ui">
<BlazorError />
</div>
<ReconnectModal />
<script src="@Assets["_framework/blazor.web.js"]"></script>
</body>
</html>
@code {
public static IComponentRenderMode InteractiveServerWithoutPrerendering { get; } =
new InteractiveServerRenderMode(prerender: false);
}
Components/Routes.razor
If your old router contains customizations, copy them to the new Routes.razor. Replace the <NotFound> fragment with the NotFoundPage parameter.
<Router AppAssembly="@typeof(Program).Assembly"
AdditionalAssemblies="[typeof(DevExpress.ExpressApp.Blazor.BlazorApplication).Assembly]"
NotFoundPage="typeof(Pages.NotFound)">
<Found Context="routeData">
<RouteView RouteData="@routeData" />
</Found>
</Router>
Update the Project File
Project templates use SDK’s default content items. In most cases, you do not need to change the project file. However, you may need to update the item list in SolutionName.Blazor.Server.csproj. This is necessary if the project explicitly defines content items (for example, it contains <EnableDefaultContentItems>false</EnableDefaultContentItems> or <Content Include="Pages\_Host.cshtml" />).
Remove obsolete items. Remove
ContentandNoneitems for App.razor and Pages/_Host.cshtml. Also remove the Compile item for Startup.cs, if present.Add new Razor components. Add
Contentitems for the new .razor files. Otherwise, the build fails with error BLAZOR102.- Do not explicitly include the reconnection modal’s CSS and JavaScript files. Do not add ReconnectModal.razor.css and ReconnectModal.razor.js as
Contentitems. The SDK includes these files automatically. An explicit item for the .razor.css causes error BLAZOR101. - Include the wwwroot folder. Include files in wwwroot as content items. The
MapStaticAssets()method serves only files included in the build’s static asset manifest. If these files are missing from the manifest, requests for assets such as css/site.css may return the application page instead of the requested files. As a result, the UI may appear without its styles and images.
<ItemGroup>
<Content Include="Components\App.razor" />
<Content Include="Components\Routes.razor" />
<Content Include="Components\Pages\NotFound.razor" />
<Content Include="Components\Layout\ReconnectModal.razor" />
<Content Include="_Imports.razor" />
<Content Include="wwwroot\**" />
</ItemGroup>
Step 3. Update Program.cs to Support Model Editor Design-Time Execution
Remove the IDesignTimeApplicationFactory implementation from Blazor, Middle Tier and Web API Service projects. The Model Editor finds a factory without this implementation:
- ASP.NET Core Blazor: The BlazorApplication class implements
IDesignTimeApplicationFactory. - Middle Tier and Web API Service: The DevExpress.ExpressApp.CodeAnalysis NuGet package generates a factory. Templates reference this package. We recommend that your project references it as well.
The factory runs Program.cs up to the builder.Build() call to get registered services. As a result, code placed before builder.Build() runs when the Model Editor opens. If such code should run only at runtime, wrap it in the following condition: if(!ModuleHelper.IsDesignMode).
For example, if your Blazor application uses the Middle Tier option, Program.cs starts the security server. In previous versions, this call had no condition. Add the condition, as in the v26.2 template. Otherwise, the security server starts each time you open the Model Editor:
#if DEBUG
if(!ModuleHelper.IsDesignMode) {
Initialization.RunSecurityServer();
}
#endif
Step 4. Update Launch Profiles in Blazor
(Optional)
The new Blazor template modifies the profiles section in the Properties/launchSettings.json file as follows:
- Removes the
SolutionName.Blazor.Serverprofile. - Adds the
httpsandhttpprofiles (port numbers do not change). - Keeps the
IISExpressprofile only if the project uses Windows Active Directory authentication.
Middle Tier and Web API Service launch profiles do not change.
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
Step 5. Update Integration Tests
Your test projects may host the application with the Startup class (for example, UseStartup\<Startup> with TestServer, or WebApplicationFactory\<Startup>). In such projects, use the Program class generated from top-level statements instead of Startup. In .NET 10, the Program class is public, and you do not need to declare it for tests.
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
namespace SolutionName.Tests;
public class TestHostFactory : WebApplicationFactory<Program> {
protected override void ConfigureWebHost(IWebHostBuilder builder) {
builder.UseEnvironment("Development");
// Register test-specific services here.
}
}
Verify the Migration
Check the following items after migration:
- The solution builds, and a search finds no references to the
Startupclass, _Host.cshtml, or blazor.server.js. - The Blazor application starts and displays the logon window and the start View.
- When you open a View URL in a new browser tab or press F5, the same View appears.
- An unknown URL (for example,
/a/b/c) displays the following message: “Sorry, there’s nothing at this address.” - Styles, images, and scripts load without errors (check the browser’s developer tools). Requests for wwwroot files (for example, css/site.css) return file content, not the application page.
- The
--helpand--updateDatabasecommand-line arguments work as before. - The Middle Tier and Web API Service start, and the client application can log in.
- The Model Editor opens in all migrated projects.