如何在 .NET Core 3.1 WebAPI 中托管 Angular 应用程序?

Wat*_*ont 10 c# single-page-application .net-core asp.net-core asp.net-core-webapi

我想通过根路由/和 REST API提供我的 Angular 应用程序/api/*。对于 Angular 路由,除了对现有文件(例如媒体文件)和我的 API 控制器路由的请求之外,我必须将所有请求重定向到 /index.html。

使用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(); });
    }
}
Run Code Online (Sandbox Code Playgroud)

Max*_*Ast 10

您错过了 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
});
Run Code Online (Sandbox Code Playgroud)

通过返回单页应用程序 (SPA) 的默认页面,处理中间件链中从这一点开始的所有请求。

这个中间件应该放在链的后面,以便其他用于提供静态文件、MVC 操作等的中间件优先。

- https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.spaapplicationbuilderextensions.usespa


更新:如果您只想将特定路线映射到 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
        });
    }
);
Run Code Online (Sandbox Code Playgroud)


Mat*_*ias 5

我遇到了同样的问题,但app.UseSpa(...)没有工作,因为我猜我缺少一些依赖项。

您也可以添加endpoints.MapFallbackToFile("/index.html");in app.UseEndpoints(..),它是Microsoft.AspNetCore.StaticFiles程序集的一部分。

所以它看起来像这样:

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
    endpoints.MapFallbackToFile("/index.html");
});
Run Code Online (Sandbox Code Playgroud)

来源:https ://weblog.west-wind.com/posts/2020/Jul/12/Handling-SPA-Fallback-Paths-in-a-Generic-ASPNET-Core-Server#server-side-navigation-of-客户端路由