[英]How to host an Angular app inside .NET Core 3.1 WebAPI?
我想通過根路徑/
和 REST API 通過/api/*
提供我的 Angular 應用程序。 For the Angular routing I have to redirect all requests to /index.html except the requests for existing files (eg media files) and my API controller routes.
有了下面的Startup.cs
,它就可以工作了:
以下不起作用:刷新或直接打開http://localhost:5000/home會以 404 結束。我猜/home
沒有重定向到 index.html。 我在這里缺少什么?
public class Startup
{
private readonly IWebHostEnvironment _webHostEnvironment;
public Startup(IWebHostEnvironment webHostEnvironment)
{
_webHostEnvironment = webHostEnvironment;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddSpaStaticFiles(options =>
{
options.RootPath = "wwwroot";
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseDefaultFiles();
app.UseSpaStaticFiles();
app.UseCors();
app.UseSwagger();
app.UseSwaggerUI(c => { /*...*/ });
app.UseRouting();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
}
對於 SPA 托管,您缺少一件重要的事情:
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
});
通過返回單頁應用程序 (SPA) 的默認頁面來處理中間件鏈中的所有請求。
這個中間件應該放在鏈的后面,以便為 static 文件、MVC 操作等提供服務的其他中間件優先。
更新:如果您只想 map 到 index.html 的特定路線,即以http://localhost/ui/
開頭的所有內容,您可以將其與app.MapWhen
結合使用
app.MapWhen(
context => context.Request.Path.StartsWithSegments("/ui/", StringComparison.OrdinalIgnoreCase),
cfg =>
{
cfg.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
});
}
);
我有同樣的問題,但app.UseSpa(...)
沒有工作,因為我想我錯過了一些依賴。
或者你可以添加endpoints.MapFallbackToFile("/index.html");
在app.UseEndpoints(..)
中,它是Microsoft.AspNetCore.StaticFiles
程序集的一部分。
所以它看起來像這樣:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapFallbackToFile("/index.html");
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.