dotnet 构建 - 出现错误“无法返回默认页面 '/index.html'”

问题描述 投票:0回答:8

尝试将我的项目生成为exe文件,但出现错误:

之前:“dotnet build -r win10-x86”就可以了

运行生成的exe后,一切都ok了:

indows DPAPI to encrypt keys at rest.
Hosting environment: Production
Content root path: C:....\currencyColution\correncyProject\bin\Debug\netcoreapp2.1\win10-x86
Now listening on: http://localhost:5000
Now listening on: https://localhost:5001
Application started. Press Ctrl+C to shut down.

加载页面后有些磨损,更准确地说是找不到index.html:

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 GET http://localhost:5000/
fail: Microsoft.AspNetCore.Server.Kestrel[13]
      Connection id "0HLG91TC2H0UO", Request id "0HLG91TC2H0UO: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.

Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SpaServices.AngularCli;
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.Swagger;
using System;
using System.IO;
using Microsoft.AspNetCore.Http;

namespace AspNetCore2Ang6Template
{
  public class Startup
  {
  
    public void ConfigureServices(IServiceCollection services)
    {
      services.AddMvc();
      services.AddSpaStaticFiles(c =>
      {
        c.RootPath = "wwwroot";
      });

    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
      if (env.IsDevelopment())
      {
        app.UseDeveloperExceptionPage();
      }

      app.UseDefaultFiles();
      app.UseStaticFiles();
      app.UseSpaStaticFiles();
      app.UseMvc(routes =>
      {
        routes.MapRoute(name: "default", template: "{controller}/{action=index}/{id}");
      });

      app.UseSpa(spa =>
      {
        spa.Options.SourcePath = "wwwroot";
      });

    }
  }
}

我不使用 Angular 和其他一些,只是尝试打开 wwwroot/index.html

文件:

货币项目

wwwroot

Program.cs

Startup.cs

在 VS 中测试,一切正常,但不能通过 exe 构建器

像 dev : dotnet run 一样启动,然后它可以在 localhost:58893/ 上运行,但是在 localhost:5000 上构建的 prod dotnet 有什么问题

启动设置:

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:58842/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "AspNetCore2Ang6Template": {
      "commandName": "Project",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "http://localhost:58893/"
    }
  }
}
c# .net asp.net-mvc binary
8个回答
17
投票

检查 angular.json 文件使用

"outputPath": "dist",

和启动文件

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

7
投票

通过比较现有的 Angular Asp net core 模板解决了这个问题,我做了以下代码更改。

在csproj文件中:

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

在Startup.cs中

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

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

在 Angular angular.json

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

3
投票

问题来自于当您使用 dotnet build 命令构建项目时,未复制 wwwroot 文件夹。

我重现了你的问题,为了修复它,我复制了输出中的文件夹并且它起作用了。

您应该使用发布命令来测试生产。

在任何一种情况下,这两个命令都不会复制 wwwroot 文件夹。


2
投票

就我而言,这是因为我添加了一个名为“LocalDevelopment”的新环境,但没有更新 Startup.cs 中 IsEnvironment 调用的目标

app.UseSpa(spa =>
{
    spa.Options.SourcePath = "ClientApp";

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

2
投票

我发现发生此错误的另一个原因是您的控制器路由属性与请求 URL 不完全匹配。

例如您的客户要求是:

https://myapp/myapi/mycontroller/myapiaction

但是 dotnet 应用程序中的控制器与预期端点的属性不匹配

// Note api in the route doesn't match myapi in the request
[ApiController]
[Route("api/[controller]/[action]")] 
public class MyController
   :
   :

0
投票

在 git 分支切换后,这发生在我身上。
我必须再次安装节点模块:

npm install    

来自 GitHub 上的这个answer。请注意,只有当您使用 Node.js 作为前端堆栈的一部分时,此解决方案才有帮助。


0
投票

对我来说,这是 enviroment.prod.ts 中的类型错误

pathApi: "/api/"
,我刚刚删除了最后一个“/”


0
投票

我在 Visual Studio 更新后发生了这种情况,其中某些功能未正确安装。
我的解决方案是清理 Visual Studio 缓存:

  1. 关闭 Visual Studio(确保任务管理器中不存在 devenv.exe)。
  2. 删除
    %USERPROFILE%\AppData\Local\Microsoft\VisualStudio\xx.x\ComponentModelCache 
    目录。
  3. 重新启动 Visual Studio。

然后尝试再次运行该应用程序。
可能会建议您安装该功能:Development time IIS support for ASP.NET Core

© www.soinside.com 2019 - 2024. All rights reserved.