Using the latest default web app template, e.g. dotnet new blazorserver
, if I change my environment from Development
to, say, LocalDevelopment
, debugging locally I lose all my styling because my site.css file will not be found (we use this custom environment when debugging locally, to differentiate from running on our shared Development web server.)
I believe this is because, per the docs,
static web assets are enabled by default in the Development environment. To support assets in other environments when running from build output, call
UseStaticWebAssets
on the host builder inProgram.cs
.
One way to do this, using the .NET 3.1/5 style hosting model, is as follows, to enable UseStaticWebAssets:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStaticWebAssets();
webBuilder.UseStartup<Startup>();
});
My question is, how do I accomplish this using the .NET 6 style hosting model? We want to use the new model for all our new apps. I've tried the following:
builder.WebHost.UseStaticWebAssets();
This yields this exception:
The web root changed from "C:\Web\BlazorServerApp\wwwroot" to "C:\Web\BlazorServerApp\". Changing the host configuration using WebApplicationBuilder.WebHost is not supported. Use WebApplication.CreateBuilder(WebApplicationOptions) instead.
and I've tried this:
builder.Host.ConfigureWebHost(c => c.UseStaticWebAssets());
and I've even tried this,
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
WebRootPath = "wwwroot"
});
This last bit of code seems to do the opposite of the intention; the root of the app seems to be set to /
rather than the intended wwwroot
, because in the browser debug window it seems to be looking for /site.css
rather than wwwroot/site.css
.
Is there any way, using the new .NET 6 hosting model / minimal templates, to enable using StaticWebAssets in a custom environment?
CodePudding user response:
that was brutal...I tried all the same with no luck, but this worked --
[assembly: HostingStartup(typeof(HelloCoreSix.MyAppHostingStartup))]
namespace HelloCoreSix
{
public class MyAppHostingStartup : IHostingStartup
{
public void Configure(IWebHostBuilder builder)
{
builder.UseStaticWebAssets();
}
}
}
Drop the above in a .cs file, it'll get picked up during bootstrap.
CodePudding user response:
The answer is obvious: you should set Web Root Path back to "wwwroot":
builder.WebHost.UseWebRoot("wwwroot");
builder.WebHost.UseStaticWebAssets();
or
WebApplicationBuilder builder = WebApplication.CreateBuilder(
new WebApplicationOptions
{
Args = args,
WebRootPath = "webroot"
}
);
builder.WebHost.UseStaticWebAssets();
I don't know the "right" way for .Net 6, but it works