首页 新闻 搜索 专区 学院

ASP.NET Core: "The SPA default page middleware could not return the default page"

0
悬赏园豆:30 [待解决问题]

基于 Angular 的 ASP.NET Core 7.0 SPA 项目日志中记录了下面的错误,请问如何消除这个错误日志?

System.InvalidOperationException: The SPA default page middleware could not return the default page '/index.html' because it was not found, and no other middleware handled the request.
Your application is running in Production mode, so make sure it has been published, or that you have built your SPA manually. Alternatively you may wish to switch to the Development environment.

   at Microsoft.AspNetCore.SpaServices.SpaDefaultPageMiddleware.<>c__DisplayClass0_0.<Attach>b__1(HttpContext context, RequestDelegate next)
   at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddlewareImpl.<Invoke>g__Awaited|8_0(ExceptionHandlerMiddlewareImpl middleware, HttpContext context, Task task)
问题补充:

请求的路径是根路径 /,只是偶尔会出现这个错误日志

对应的 ASP.NET Core 开源代码 SpaDefaultPageMiddleware.cs#L54

dudu的主页 dudu | 高人七级 | 园豆:34217
提问于:2023-03-17 14:54
< >
分享
所有回答(1)
0

从 SpaDefaultPageMiddleware 源码看 SpaDefaultPageMiddleware.cs#L54

app.Use((context, next) =>
{
    // If we have an Endpoint, then this is a deferred match - just noop.
    if (context.GetEndpoint() != null)
    {
        return next(context);
    }

    var message = "The SPA default page middleware could not return the default page " +
        $"'{options.DefaultPage}' because it was not found, and no other middleware " +
        "handled the request.\n";

    //...
    throw new InvalidOperationException(message);    
}

context.GetEndpoint() 为 null,也就是请求路径 /index.html 没有对应的 endpoint 处理它,对于 SPA 场景就是 StaticFileMiddleware 没有处理这个请求,为什么没有处理?理由很简单,没有找到对应的静态文件。

基于上面的分析,重现这个问题很简单,登录到容器内将 /app/ClientApp/dist/index.html 文件重命名。

联系到我们的具体场景,当时负载均衡的健康检查地址配置为根路径 /,所以负载均衡会不停地请求 /,在某种未知的因素下会出现 StaticFileMiddleware 找不到 /app/ClientApp/dist/index.html 的情况,从而引发这个异常。

负载均衡健康检查地址现已改为 MapHealthChecks 中配置的地址。

dudu | 园豆:34217 (高人七级) | 2023-03-17 15:56
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册