Is it possible to host a blazor web application from a WPF application in .NET 9?
The situation is as following: I have a big WPF application which is used for regular operation. But now I want to have a simple webserver interface to adjust some settings via web interface. I have though of spinning up a blazor WebApplication
as following: Created a blazor project and added the WebServerService
class with Start method (as shown below). In the AddServices
the required dependency services are copied from WPF DI to blazor DI.
public void Start(){ var contentRoot = AppContext.BaseDirectory; _builder = WebApplication.CreateBuilder(new WebApplicationOptions() { Args = [], ContentRootPath = contentRoot, WebRootPath = Path.Combine(contentRoot, "wwwroot"), }); AddServices(); StaticWebAssetsLoader.UseStaticWebAssets(_builder.Environment, _builder.Configuration); _app = _builder.Build(); _app.UseExceptionHandler("/Error", createScopeForErrors: true); _app.UseHsts(); _app.UseHttpsRedirection(); _app.UseAntiforgery(); _app.MapStaticAssets(Path.Combine(contentRoot, "WebTabletUI.staticwebassets.endpoints.json")); _app.MapRazorComponents<App>() .AddInteractiveServerRenderMode(); Task.Run(() => { _app.Run("http://localhost:5000"); });}
This works but gives exceptions in the blazor web app where files are not found correctly and the CSS / JS of the website don't work properly. (If you run the blazor app from Visual studio as startup project then the website css and js work as expected.
The file that the middleware misses is the \wwwroot\WebTabletUI.styles.css
. Correct me if mistaken: This is somehow generated by blazor application. But it seems like because the base program is WPF the blazor app is not run with same environment? Am I missing some extra setup that is required to do when not running the blazor application directly?