gpt4 book ai didi

c# - Startup.cs 中 SPA 源路径的 GetCurrentDirectory() 为 VS2017 和 VS Code 返回不同的路径

转载 作者:太空宇宙 更新时间:2023-11-04 00:02:07 28 4
gpt4 key购买 nike

在我的 asp.NET core React 应用程序中,startup.cs 文件中有一个位置定义了 React 源目录的路径。

app.UseSpa(spa =>
{
var path = Path.Combine(Directory.GetCurrentDirectory(), "ClientApp");
spa.Options.SourcePath = path;
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
<小时/>

整个 Startup.csProgram.cs 文件如下所示

Program.cs

public static void Main(string[] args) {
CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup < Startup > ();

Startup.cs

public Startup(IConfiguration configuration) {
Configuration = configuration;
}

public IConfiguration Configuration {
get;
}

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) {
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration => {
configuration.RootPath = "ClientApp/build";
});
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
} else {
app.UseExceptionHandler("/Error");
app.UseHsts();
}

//app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();

app.UseMvc(routes => {
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});

app.UseSpa(spa =>
{
var path = Path.Combine(Directory.GetCurrentDirectory(), "ClientApp");
spa.Options.SourcePath = path;
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
}
<小时/>

VS 2017 Solution

VS 2017 解决方案

使用默认的IIS Express配置开始调试

VS Code Folder

VS 代码文件夹

使用launch.json中默认的.NET Core Launch (web)配置开始调试

<小时/>

但在这种情况下,Directory.GetCurrentDirectory() 会为 VS 2017VSCode 返回不同的路径。 (这可能是由于上下文而预期的)。SPA 源文件夹 ClientAppStartup.cs、其他必要文件和 Controllers 文件夹一起驻留在 SolutionFolder/Presentation/ 中。 Presentation 设置为 StartUp 项目。

如何相对地定义该路径,使其不会根据 IDE、环境或构建而改变?

最佳答案

解决了我猜的问题。在 VS2017 中设置为启动项目也会将当前工作目录设置为该路径。这会反射(reflect)在 CurrentRoothPathDirectory.GetCurrentDirectory() 的值中。

但是在使用默认调试配置的 VSCode 中,当前目录指向打开的文件夹的根目录(而不是任何项目或子文件夹)。

我必须将 launch.jsoncwd 的值从 "${workspaceFolder}" 更改为 "${ workspaceFolder}/ReportingTool.Presentation"

根据文档:

cwd - current working directory for finding dependencies and other files

所以我不完全确定这将如何影响生产构建或其他依赖项。这暂时解决了这个问题。希望有人能进一步澄清。

关于c# - Startup.cs 中 SPA 源路径的 GetCurrentDirectory() 为 VS2017 和 VS Code 返回不同的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54171010/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com