Microsoft.AspNetCore.SpaProxy 6.0.1 - ASPNETCORE_HOSTINGSTARTUPASSEMBLIES - System.UriFormatException:无效的 URI:URI 为空

Ogg*_*las 15 .net c# asp.net reactjs asp.net-core

尝试在启动时添加Microsoft.AspNetCore.SpaProxy 6.0.1NuGet 时出现以下错误:

失败:Microsoft.AspNetCore.Server.Kestrel[13] 连接 ID“X”,请求 ID“Y:00000001”:应用程序引发了未处理的异常。System.UriFormatException:无效的 URI:URI 为空。在System.Uri.CreateThis(字符串uri,布尔dontEscape,UriKind uriKind,UriCreationOptions&creationOptions)在System.Uri..ctor(字符串uriString)在Microsoft.AspNetCore.SpaProxy.SpaProxyMiddleware.Invoke(HttpContext上下文)在Microsoft.AspNetCore.Hosting .HostingApplication.ProcessRequestAsync(上下文上下文)位于 Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 应用程序)

在 .NET 5 中,提供了以下代码Startup.cs

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

    if (env.IsDevelopment())
    {
        spa.UseReactDevelopmentServer(npmScript: "start");
    }
});
Run Code Online (Sandbox Code Playgroud)

这在 .NET 6 中不存在,而是launchSettings.json有一个环境变量:"ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"

我知道它可以工作,因为使用模板和 .NET 6 的新项目ASP.NET Core with React.js启动没有问题。

使用 TypeScript 创建 React App 项目需要Microsoft.AspNetCore.SpaProxy向现有 .NET 6 ASP.NET Core 应用程序添加什么?

https://create-react-app.dev/docs/adding-typescript/

我尝试从工作项目中添加文件aspnetcore-https.jsaspnetcore-react.js、 。.env.env.development

使用这些值进行编辑Program.cs

app.UseStaticFiles();
app.UseRouting();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}");

app.MapFallbackToFile("index.html");
Run Code Online (Sandbox Code Playgroud)

修改package.json为如下所示:

"prestart": "node aspnetcore-https && node aspnetcore-react",
"start": "rimraf ./build && react-scripts start",
Run Code Online (Sandbox Code Playgroud)

我已经安装rimraf并且命令npm run start可以npm run build工作。

Ogg*_*las 17

SpaProxyServerUrl这个特定的错误需要一个名为的变量.csproj。要使一切按预期工作还需要其他一些事情,因此完整的代码如下:

launchSettings.json:

{
  "$schema": "https://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:39330",
      "sslPort": 44358
    }
  },
  "profiles": {
    "Project.Web": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "https://localhost:7178;http://localhost:5178",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Program.cs:

app.MapFallbackToFile("index.html");
Run Code Online (Sandbox Code Playgroud)

.csproj:

<PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <UserSecretsId>aspnet-Project.Web-12345678-1234-1234-1234-123456789012</UserSecretsId>
    <SpaRoot>ClientApp\</SpaRoot>
    <SpaProxyServerUrl>https://localhost:44358</SpaProxyServerUrl>
    <SpaProxyLaunchCommand>npm start</SpaProxyLaunchCommand>
</PropertyGroup>

<ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.1" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="6.0.1" />
    <PackageReference Include="Microsoft.AspNetCore.SpaProxy" Version="6.0.1" />
    <PackageReference Include="Microsoft.Identity.Web" Version="1.16.0" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
</ItemGroup>

<ItemGroup>
    <!-- Don't publish the SPA source files, but do show them in the project files list -->
    <Content Remove="$(SpaRoot)**" />
    <None Remove="$(SpaRoot)**" />
    <None Include="$(SpaRoot)**" Exclude="$(SpaRoot)node_modules\**" />
</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="npm run build" />

    <!-- Include the newly-built files in the publish output -->
    <ItemGroup>
        <DistFiles Include="$(SpaRoot)build\**" />
        <ResolvedFileToPublish Include="@(DistFiles->'%(FullPath)')" Exclude="@(ResolvedFileToPublish)">
            <RelativePath>wwwroot\%(RecursiveDir)%(FileName)%(Extension)</RelativePath>
            <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
            <ExcludeFromSingleFile>true</ExcludeFromSingleFile>
        </ResolvedFileToPublish>
    </ItemGroup>
</Target>
Run Code Online (Sandbox Code Playgroud)