Skip to content
This repository has been archived by the owner. It is now read-only.

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

Closed
jrmcdona opened this issue Feb 2, 2018 · 18 comments

Comments

@jrmcdona
Copy link

@jrmcdona jrmcdona commented Feb 2, 2018

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()
@grapehunter
Copy link

@grapehunter grapehunter commented Feb 5, 2018

I reproduce the same issue too.
I made a middleware to catch all unhandled exceptions to response an error .

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.

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

@jrmcdona
Copy link
Author

@jrmcdona jrmcdona commented Feb 5, 2018

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

@SteveSandersonMS
Copy link
Member

@SteveSandersonMS SteveSandersonMS commented Feb 7, 2018

@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!

@jrmcdona
Copy link
Author

@jrmcdona jrmcdona commented Feb 7, 2018

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

@jrmcdona
Copy link
Author

@jrmcdona jrmcdona commented Feb 7, 2018

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

@delarocka
Copy link

@delarocka delarocka commented Feb 25, 2018

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

@yuessir
Copy link

@yuessir yuessir commented Apr 8, 2018

$ASPNETCORE_ENVIRONMENT=Development dotnet run

or
$export ASPNETCORE_Environment=Development
$dotnet run

@OutSorcerer
Copy link

@OutSorcerer OutSorcerer commented May 21, 2018

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.

@LeandroCarvalho
Copy link

@LeandroCarvalho LeandroCarvalho commented May 27, 2018

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

@kwaazaar
Copy link

@kwaazaar kwaazaar commented Jul 20, 2018

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.

@DaleCox
Copy link

@DaleCox DaleCox commented Jul 26, 2018

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.

@dlahmad
Copy link

@dlahmad dlahmad commented Aug 27, 2018

@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".

@joshpearce
Copy link

@joshpearce joshpearce commented Aug 31, 2018

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

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

@alaatm
Copy link

@alaatm alaatm commented Sep 2, 2018

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.

@maxisam
Copy link

@maxisam maxisam commented Sep 27, 2018

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.

@mjtpena
Copy link

@mjtpena mjtpena commented Oct 12, 2018

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

@sathishid
Copy link

@sathishid sathishid commented Nov 19, 2018

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",

@ColinM9991-zz
Copy link

@ColinM9991-zz ColinM9991-zz commented Dec 14, 2018

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet