为什么我需要在 Startup Configure 中的 UseSpa 之前调用 UseSignalR

Why do I need to call UseSignalR before UseSpa in Startup Configure

我在将 Angular 用作 SPA 的 .Net Core Web 应用程序中使用 SignalR 时遇到了一个令人沮丧的问题。在与客户端协商的 SignalR 上,Web 服务器将响应 404 错误。

此 GitHub 期中描述了确切的问题和解决方案。 https://github.com/aspnet/SignalR/issues/2528

我的问题是,为什么调用 UseSignalR 和 UseSpa 的顺序很重要? 为什么这行得通并且 Web 服务器接受 SignalR 客户端通信...

app.UseSignalR(routes => 
    { 
        ... 
    });

app.UseSpa(spa =>
    {
        ...
    });

并且此配置会导致 Web 服务器响应 404

app.UseSpa(spa =>
    {
        ...
    });

app.UseSignalR(routes => 
    { 
        ... 
    });

如果你 read the documentation for SpaApplicationBuilderExtensions.UseSpa,你清楚地看到:

Handles all requests from this point in the middleware chain by returning the default page for the Single Page Application (SPA).

This middleware should be placed late in the chain, so that other middleware for serving static files, MVC actions, etc., takes precedence.

因此 SpaMiddleware 捕获 每个 到达其管道点的请求,并尝试将其作为对 SPA 主页的请求处理(Angular/React/other).

顺序总是很重要:ASP.NET核心使用一个管道,所以你放入这个管道中的每个中间件都会按顺序执行。如果中间件在不调用管道的其余部分的情况下处理请求,则请求会在那里停止并返回响应。