无法在工作项目目录之外发布 ASP.Net Core SPA 应用程序

问题描述

我正在使用 AngularASP.Net 构建应用程序。 我使用过 ASP.Net Core & Angular web template(包含在 Visual Studio 中)。 但是,我的前端源代码没有像定义的模板一样放在 ClientApp 文件夹中(因为我的项目要求)

我设置了一个环境变量,它是:APPLICATON_FRONT_END_PATH,它指向我的项目工作目录之外的目录。比如说:

  • 我的项目位于:H:\Back-end\asp-net\my-app
  • 我的前端源代码位于:H:\Front-end\angular\my-app
  • 环境(上面提到的)指向 H:\Front-end\angular\my-app

我已将 Startup.cs 中的实现更改为:

public class Startup
{
    #region Constructor

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
        _environment = Environment.GetEnvironmentVariable("APPLICATON_FRONT_END_PATH");
    }

    #endregion

    #region Properties

    private readonly string _environment;

    public IConfiguration Configuration { get; }

    #endregion

    #region Methods

    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application,visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews()
            .AddNewtonsoftJson(options =>
            {
                var camelCasePropertyNamesContractResolver = new CamelCasePropertyNamesContractResolver();
                options.SerializerSettings.ContractResolver = camelCasePropertyNamesContractResolver;
            });

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

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app,IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
            app.UseDeveloperExceptionPage();

        // Use routing.
        app.UseRouting();
        
        // Use static file.
        app.UseStaticFiles();
        if (!env.IsDevelopment())
            app.UseSpaStaticFiles();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                "default","{controller=Home}/{action=Index}/{id?}");
        });
        
        app.UseSpa(spa =>
        {
            // To learn more about options for serving an Angular SPA from ASP.NET Core,// see https://go.microsoft.com/fwlink/?linkid=864501

            
            spa.Options.SourcePath = $"{_environment}";


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

    #endregion
}

并将我的 .csproj 更改为:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net5.0</TargetFramework>
    <OutputType>WinExe</OutputType>
    <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
    <TypeScriptToolsVersion>Latest</TypeScriptToolsVersion>
    <IsPackable>false</IsPackable>
    <SpaRoot>$(APPLICATON_FRONT_END_PATH)\</SpaRoot>
    <DefaultItemExcludes>$(DefaultItemExcludes);$(SpaRoot)node_modules\**</DefaultItemExcludes>
  </PropertyGroup>

  <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>
  
  <ItemGroup>
    <Folder Include="wwwroot\" />
  </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 -- --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>
        <ExcludeFromSingleFile>true</ExcludeFromSingleFile>
      </ResolvedFileToPublish>
    </ItemGroup>
  </Target>
</Project>

我可以顺利运行我的项目,但是,当我发布应用程序时,出现错误:

C:\Program Files\dotnet\sdk\5.0.201\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.Publish.targets(197,5):错误 MSB3541:文件的值无效"H:\Back-end\asp-net\my-app\obj\Release\net5.0\PubTmp\Out\H:\Front-end\angular\my-app\dist\app-main\0-es2015 .aaca7edec797253393da.js”。不支持指定路径的格式。

有人可以帮我吗? 谢谢

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...