简体   繁体   English

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

[英]How to host an Angular app inside .NET Core 3.1 WebAPI?

I want to provide my Angular app through the root route / and the REST API through /api/* .我想通过根路径/和 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. 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.

With the Startup.cs below it's close to be working:有了下面的Startup.cs ,它就可以工作了:

The following is not working: Refreshing or opening directly http://localhost:5000/home will end up in a 404. I guess /home is not redirected to the index.html.以下不起作用:刷新或直接打开http://localhost:5000/home会以 404 结束。我猜/home没有重定向到 index.html。 What I'm missing here?我在这里缺少什么?

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(); });
    }
}

Your are missing one important thing for SPA hosting:对于 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
});

Handles all requests from this point in the middleware chain by returning the default page for the Single Page Application (SPA).通过返回单页应用程序 (SPA) 的默认页面来处理中间件链中的所有请求。

This middleware should be placed late in the chain, so that other middleware for serving static files, MVC actions, etc., takes precedence.这个中间件应该放在链的后面,以便为 static 文件、MVC 操作等提供服务的其他中间件优先。

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


Update: If you only want to map a specific route to the index.html ie everything starting with http://localhost/ui/ you can combine it with app.MapWhen更新:如果您只想 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
        });
    }
);

I had the same problem but app.UseSpa(...) did not work as I guess I was missing some dependecies.我有同样的问题,但app.UseSpa(...)没有工作,因为我想我错过了一些依赖。

Alternativele you could add endpoints.MapFallbackToFile("/index.html");或者你可以添加endpoints.MapFallbackToFile("/index.html"); in app.UseEndpoints(..) , which is part of the Microsoft.AspNetCore.StaticFiles assembly.app.UseEndpoints(..)中,它是Microsoft.AspNetCore.StaticFiles程序集的一部分。

So it would look like this:所以它看起来像这样:

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
    endpoints.MapFallbackToFile("/index.html");
});

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Ubuntu上托管/发布我的.Net Core WebAPI? - How do I host/publish my .Net Core WebAPI on Ubuntu? 如何在Azure上托管和部署ASP.Net Core 2.0 WebAPI? - How to Host and Deploy ASP.Net core 2.0 webapi on azure? 如何将 .NET Core 3.1 API web 应用程序作为 Z0F4137ED1502B5045426083AA258 服务托管? - How to host a .NET Core 3.1 API web application as windows service? .NET Core 3.1 WebApi - 来自另一个 WebApi 的直通 JSON 响应 - .NET Core 3.1 WebApi - Passthrough JSON response from another WebApi ASP.NET Core2 WebAPI和角度应用程序未在页面中呈现 - asp.net core2 webapi and angular app not rendering in the page Cors 在 webapi 上添加 app.useauthentication 时失败 .net 核心 3.1 - Cors fail when add app.useauthentication on webapi .net core 3.1 如何在 .net core 3.1 应用程序中注入 Log4net 日志记录 - How to inject Log4net logging in .net core 3.1 app .NET Core 中 WebAPI 的 Angular UI,但主要目的仍然是 WebAPI,而不是前端应用程序 - Angular UI for a WebAPI in .NET Core while still the primary purpose is a WebAPI, not a frontend App ASP.NET Core 3.1:如何将驼峰 json 从 webapi 反序列化为 pascalcase - ASP.NET Core 3.1: How to deserialize camelcase json from webapi to pascalcase .Net Core 3.1 WebAPI 如何序列化 IEnumerable<t> 来自 POST 正文</t> - .Net Core 3.1 WebAPI How to serialize IEnumerable<T> from POST body
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM