在一个 ASP.NET Core 3.1 + Angular 8.2 的 SPA 项目中,POST 请求一个不存在的路径就会出现下面的错误:
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, Func`1 next)
at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Builder.Extensions.MapWhenMiddleware.Invoke(HttpContext context)
请问如何解决?
查看 ASP.NET Core 的源码 SpaDefaultPageMiddleware.cs#L47 知道了异常是在下面的代码中抛出的。
// If we have an Endpoint, then this is a deferred match - just noop.
if (context.GetEndpoint() != null)
{
return next();
}
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";
后来采用的解决方法
app.MapWhen(
context => context.Request.Method == HttpMethod.Head.Method || context.Request.Method == HttpMethod.Get.Method,
frontEndApp =>
{
frontEndApp.UseSpa(spa =>
{
// ...
});
});
tks!
app.UseWhen(context => HttpMethods.IsGet(context.Request.Method), builder =>
{
builder.UseSpa(spa =>
{
});
});
The SPA default page middleware could not return the default page '/index.html'