Javascriptservices: The SPA default page middleware could not return the default page '/index.html' not found when using 2.0.0-rc1-final

Created on 2 Feb 2018  路  18Comments  路  Source: aspnet/JavaScriptServices

I created a project with
dotnet new --install Microsoft.DotNet.Web.Spa.ProjectTemplates::2.0.0-rc1-final
dotnet new angular

Here is the error:

Application started. Press Ctrl+C to shut down.
fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0]
      An unhandled exception has occurred: 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.

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, Func`1 next)
   at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>d__6.MoveNext()
fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0]
      An exception was thrown attempting to execute the error handler.
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, Func`1 next)
   at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>d__6.MoveNext()
fail: Microsoft.AspNetCore.Server.Kestrel[13]
      Connection id "0HLBABQBRVS28", Request id "0HLBABQBRVS28:00000001": An unhandled exception was thrown by the application.
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, Func`1 next)
   at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware.<Invoke>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame`1.<ProcessRequestsAsync>d__2.MoveNext()
fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0]
      An unhandled exception has occurred: 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.

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, Func`1 next)
   at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>d__6.MoveNext()
fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0]
      An exception was thrown attempting to execute the error handler.
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, Func`1 next)
   at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>d__6.MoveNext()
fail: Microsoft.AspNetCore.Server.Kestrel[13]
      Connection id "0HLBABQBRVS2A", Request id "0HLBABQBRVS2A:00000001": An unhandled exception was thrown by the application.
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, Func`1 next)
   at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware.<Invoke>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame`1.<ProcessRequestsAsync>d__2.MoveNext()

Most helpful comment

@jrmcdona I got same error. Fixed after setting environment variable ASPNETCORE_Environment=Development.

All 18 comments

I reproduce the same issue too.
I made a middleware to catch all unhandled exceptions to response an error .
```c#
public class ErrorHandlingMiddleware
{
private readonly RequestDelegate next;

public ErrorHandlingMiddleware(RequestDelegate next)
{
    this.next = next;
}

public async Task Invoke(HttpContext context, ILogger<ErrorHandlingMiddleware> _logger)
{
    try
    {
        await next(context);
    }
    catch (Exception ex)
    {
            await HandleExceptionAsync(context, ex, _logger);
    }
}

private static Task HandleExceptionAsync(
    HttpContext context,
    Exception exception,
    ILogger<ErrorHandlingMiddleware> _logger)
{
    var code = HttpStatusCode.InternalServerError; // 500 if unexpected
    _logger.LogError("Unhandled excetion. {0}", exception);
    var result = JsonConvert.SerializeObject(
        new ErrorResponse
        {
            Error = ErrorResponse.Errors.InnerException,
            ErrorDescription = exception.Message
        });
    context.Response.ContentType = "application/json";
    context.Response.StatusCode = (int)code;
    return context.Response.WriteAsync(result);
}

}

And I found that every page display as json object.
So I modified some lines to avoid catching this exception,and it works fine now.
```c#
try
{
    await next(context);
}
catch (Exception ex)
{
    if (ex is InvalidOperationException && ex.Message.StartsWith("The SPA default page middleware could not return the default page"))
    {

    }
    else
    {
        await HandleExceptionAsync(context, ex, _logger);
    }
}

I didn't make a single modification. Just tried to build and run.

@jrmcdona Not sure if I'm misreading your report, but it looks like the cause and solution are both specified in the error message you've posted:

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.

If this is not the cause, please let us know what other repro steps we can use to produce this issue. Thanks!

I did build and run.

dotnet build
dotnet run

Am I missing something?

Just tried it again. Same effect. I have made no mods.
Thanks

Corrupt/incomplete node_modules. Delete than and did an npm install and all is ok now. Thanks

@jrmcdona I got same error. Fixed after setting environment variable ASPNETCORE_Environment=Development.

$ASPNETCORE_ENVIRONMENT=Development dotnet run

or
$export ASPNETCORE_Environment=Development
$dotnet run

Just switching to development mode is not a solution, for example it disables server-side rendering.

I also had that exception occasionally and it seems that the reason was not enough CPU resources for Node.js process.

He had the same problem.

The error occurred because the dist folder is not created in ClientApp, see configuration.

     public void ConfigureServices (IServiceCollection services)
     {
         services.AddMvc ();

         // In production, the Angular files will be served from this directory
         services.AddSpaStaticFiles (configuration =>
         {
             configuration.RootPath = "ClientApp/dist";
         });
     }

Remember that this setting is of production, probably the ASPNETCORE_Environment=Development variable was not created correctly

To solve the problem I installed the global cli angular npm install - g @angular/cli and executed the ng build command in the ClientApp folder

Because this projecttype has both .NET code and html/css/javascript, it needs additional steps to fully build a working product. The csproj has an additional target which takes care of that (PublishRunWebpack). This target is not invoked during build, but only during publish (eg: dotnet publish -c Release).

Publish is what you use when creating a release-version, probably to be installed on a different server or to create a container image. When developing, you don't want all these steps. Therefore the Configure-method in Startup.cs contains this code:

if (env.IsDevelopment())
{
    spa.UseAngularCliServer(npmScript: "start");
}

This will use "npm run start" (which may use ng --serve for example) to host the html-part and therefore allow for a comfortable web-dev experience. This is also why some people had success setting the ASPNETCORE_Environment variable to 'Development'. However, that is not how things are supposed to be used.

I ran into this same issue. The root cause of my issue was that Angular 6 default config appends the project name to the dist path pushing all the built code down an directory. The fix for me was to alter the Angular.json file and remove the additional folder that the CLI added, matching the expected format the .NET code is checking against.

@DaleCox This seems to be my problem too. Which changes did you make to the angular.json to prevent the extra folder creation?

Thank you very much!

EDIT: I found it. In angular.json change "ouputPath". Normally it seems to be "dist/{ProjectName}". Change this to just "dist".

It's an IIS Default Document issue. Just add the following to your web.config:

<system.webServer>
   ...
      <defaultDocument enabled="false" />
</system.webServer>

Having this error too. The index.html file is there. I don't get it!

UPDATE
Stopping the Azure website then running it again seem to resolve the issue.

I got this error as well. The interesting part is it doesn't always throw this error. Most of time, it works. However, it doesn't work sometime. It seems like if I remove index.html from the dist folder, it will trigger this error. But the problem is no one remove that index.html.

My server environment is IIS10 + Windows 2016.

This happened to my Azure App Service. All I had to do was to restart the service. Worked like charm.

Resolved this issue by comparing existing Angular Asp net core template, I did following code changes.
In csproj file:

<TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
 <TypeScriptToolsVersion>Latest</TypeScriptToolsVersion>
 <IsPackable>false</IsPackable>
 <SpaRoot>ClientApp\</SpaRoot>
 <DefaultItemExcludes>$(DefaultItemExcludes);$(SpaRoot)node_modules\**</DefaultItemExcludes>

 <!-- Set this to true if you enable server-side prerendering -->
 <BuildServerSideRenderer>false</BuildServerSideRenderer>
 <UserSecretsId>baa2f579-d2a7-4eb4-89fb-1c171b2e2482</UserSecretsId>
 <TypeScriptToolsVersion>3.0</TypeScriptToolsVersion>

<ItemGroup>
 <TypeScriptCompile Include="App\src\app\models\user.ts" />
 <TypeScriptCompile Include="App\src\app\utils\AppContants.ts" />
 <!-- Don't publish the SPA source files, but do show them in the project files list -->
 <Content Remove="$(SpaRoot)**" />
 <None Include="$(SpaRoot)**" Exclude="$(SpaRoot)node_modules\**" />
</ItemGroup>

<ItemGroup>
 <Folder Include="Properties\PublishProfiles\" />
</ItemGroup>

<Target Name="DebugEnsureNodeEnv" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('$(SpaRoot)node_modules') ">
 <!-- Ensure Node.js is installed -->
 <Exec Command="node --version" ContinueOnError="true">
   <Output TaskParameter="ExitCode" PropertyName="ErrorCode" />
 </Exec>
 <Error Condition="'$(ErrorCode)' != '0'" Text="Node.js is required to build and run this project. To continue, please install Node.js from https://nodejs.org/, and then restart your command prompt or IDE." />
 <Message Importance="high" Text="Restoring dependencies using 'npm'. This may take several minutes..." />
 <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
</Target>

<Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish">
 <!-- As part of publishing, ensure the JS resources are freshly built in production mode -->
 <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
 <Exec WorkingDirectory="$(SpaRoot)" Command="ng build --prod" />
 <Exec WorkingDirectory="$(SpaRoot)" Command="npm run build:ssr -- --prod" Condition=" '$(BuildServerSideRenderer)' == 'true' " />

 <!-- Include the newly-built files in the publish output -->
 <ItemGroup>
   <DistFiles Include="$(SpaRoot)dist\**; $(SpaRoot)dist-server\**" />
   <DistFiles Include="$(SpaRoot)node_modules\**" Condition="'$(BuildServerSideRenderer)' == 'true'" />
   <ResolvedFileToPublish Include="@(DistFiles->'%(FullPath)')" Exclude="@(ResolvedFileToPublish)">
     <RelativePath>%(DistFiles.Identity)</RelativePath>
     <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
   </ResolvedFileToPublish>
 </ItemGroup>
</Target>

In Startup.cs

services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });

 app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";
                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });

In Angular Package.json

"options": { "outputPath": "dist",

I'm having this issue appear in my server log files, but the website does function and return the index.html correctly.

ClientApp/dist exists in the publish directory alongside the API, and is archived & deployed in that format. Build is run in Production mode.

It's running .NET Core on Ubuntu 18.04.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

caesay picture caesay  路  3Comments

harsimranb picture harsimranb  路  3Comments

mounthorse-slns picture mounthorse-slns  路  3Comments

asadsahi picture asadsahi  路  3Comments

Sampath-Lokuge picture Sampath-Lokuge  路  4Comments