如何更改Blazor wasm应用程序的基本URL [英] How to change the base URL of a blazor wasm app
问题描述
为Blazor wasm托管应用程序生成的模板的基本URL以‘/’开头(即,https://localhost:5001/
用于本地开发或https://www.domain-name.xyz/
在部署时)。)我需要此基本URL为‘/app’,即(https://localhost:5001/app
)或(https://www.domain-name.xyz/app
)。
文档(here和here)说明我必须更改index.html:
中<base />
标记中的基本URL
<base href="/app/" />
并在本地开发时使用命令行参数--pathbase
:
dotnet run --pathbase=/app
我这样做了,没有对模板做任何其他更改。 然而,这对我不起作用。该应用程序的所有文件都显示404 Not Found(找不到)。
此问题here说明我还需要通过将‘/app’传递给UseBlazorFrameworkFiles来更改Blazor文件的公开位置:
app.UseBlazorFrameworkFiles("/app")
这也不能解决我的问题。
任何人都可以提供如何实现此目标的循序渐进的指导吗?这是肯定有效的。
推荐答案
您马上就到了。我不确定您要对根站点做什么,所以我添加了一个简单的登录页面,其中包含指向WASM SPA的链接。这里有一套完整的说明。
- host.html-将基准更改为
<base href="/app/" />
。这将确保SPA中的所有@Page
指令都带有app前缀。您需要尾部/
。 - host.html-将脚本引用更改为
<script src="/app/_framework/blazor.webassembly.js"></script>
。如果您托管的是单一的WASM SPA,则无需更改它即可逍遥法外。实验。 - WASM项目文件添加
StaticWebAssetBasePath
。这将使用正确的路径设置生成。
<PropertyGroup>
<StaticWebAssetBasePath>app</StaticWebAssetBasePath>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
- 在Server项目中更新
Startup
,为myWebSite/app添加新的中间件路径
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.MapWhen(ctx => ctx.Request.Path.StartsWithSegments("/app"), first =>
{
first.UseBlazorFrameworkFiles("/app");
first.UseStaticFiles();
first.UseRouting();
first.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapFallbackToFile("app/{*path:nonfile}", "app/index.html");
});
});
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
// endpoints.MapFallbackToFile("_index.cshtml");
endpoints.MapFallbackToPage("/_Index");
});
}
我已将默认登录页添加到根站点-_Index.cshtml
@page "/"
@model WebApplication2.Server.Pages._IndexModel
<h3>Hello App</h3>
<div><a href="/app">App WASM SPA</a></div>
@{
}
注意:在更新控制器url之前,FetchData不起作用
forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("/WeatherForecast");
您还可以将WASMwwwroot移到根目录中,然后在say_App.cshtml处添加启动页以启动SPA。
有关详细信息,请访问Github网站here by Javier Nelson和我撰写的一篇文章,内容是如何使用Github回购在同一网站here上托管多个水疗中心。
这篇关于如何更改Blazor wasm应用程序的基本URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!