Cannot publish ASP.Net Core SPA application outside working project directory

481 views Asked by At

I'm building an application using Angular & ASP.Net. I have used ASP.Net Core & Angular web template (included in Visual Studio). However, my front-end source code is not placed in ClientApp folder as the template defined (because of the requirement from my project)

I set an environment variable, which is: APPLICATON_FRONT_END_PATH which points to a directory outside my working directory of my project. Let say:

  • My project is at: H:\Back-end\asp-net\my-app
  • My front-end source code is at: H:\Front-end\angular\my-app
  • The enviroment (mentioned above) is point to H:\Front-end\angular\my-app

I have changed the implementation in Startup.cs as:

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
}

And changed my .csproj to this:

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

I can run my project smoothly, however, when I publish my application, I got an error:

C:\Program Files\dotnet\sdk\5.0.201\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.Publish.targets(197,5): Error MSB3541: Files has invalid value "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". The given path's format is not supported.

Can anyone help me please ? Thank you

0

There are 0 answers