ASP.Net核心-IApplicationBuilder.Map、SPA和静态文件



我想使用Asp.Net Core 2.2来托管我的Angular应用程序,并提供API请求(在/API上)。

因此,在Startup.cs的Configure中,我设置了以下内容:

app.Map("/home", config =>
{
config.UseSpa(spa =>
{
...
});
});

然而,问题是runtime.js、polyfills.js等都找不到,因为它们被引用为http://localhost:port/filename.ext

我试着用

config.UseSpaStaticFiles(new StaticFileOptions { RequestPath = "/runtime.js" });

但无济于事。

在ASP.Net Core中,在不同的路线下提供Angular SPA的秘密酱汁是什么?

编辑:回答@Michael-我本来打算最终托管多个应用程序,但我觉得这可能不值得麻烦。我希望在开发应用程序时能够做"ng服务",并在部署时在Asp.Net Core下运行。如果一个东西有效,另一个东西就会坏掉。所以决定暂时把它摆出来。

我将讨论csproj配置、package.json npm配置,当然还有Startup.cs代码。

.csproj文件

在csproj文件的底部,您会发现一组npm命令,这些命令在应用程序发布时运行。

<!--...-->
<PropertyGroup>
<SpaRoot>ClientApp</SpaRoot>
</PropertyGroup>
<!--...-->
<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' " />
<!--...-->

如果您想部署两个应用程序,则需要加倍执行所有这些部署说明。

<!--...-->
<PropertyGroup> 
<!--...-->
<SpaRoot>ClientApp</SpaRoot>
<SpaRoot2>ClientApp2</SpaRoot2>
<!--...-->
</PropertyGroup>
<!--...-->
<Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
<!--...-->
<Exec WorkingDirectory="$(SpaRoot2)" Command="npm install" />
<!--...-->

配置package.json

在开发过程中,您可能希望nodejs承载应用程序。在这种情况下,我们的服务器没有托管我们的客户端应用程序。

您需要将servepath设置为与您希望客户端应用程序用完的子目录相匹配。

// ...
"start": "ng serve --servePath /app/ --baseHref /app/",
// ...

在这一点上,不要忘记更新构建的baseHref。否则,当csproj中的脚本调用build时,它将不会指向正确的basehref。

"build": "ng build --baseHref /app/",

Startup.cs配置

还记得我在开发过程中说过服务器不托管客户端吗?我建议在开发时一次运行一个。重要的是要更新package.json servePath,以便测试url路径以及所有内容如何链接在一起。

if (env.IsDevelopment())
{
app.UseSpaStaticFiles();
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
// this is calling the start found in package.json
spa.UseAngularCliServer(npmScript: "start");
});
}
else // Production -- in the next section, 

最后,我们有了我们希望它在生产中的表现。

// how you had it, we will create a map 
// for each angular client we want to host. 
app.Map(new PathString("/app"), client =>
{
// Each map gets its own physical path
// for it to map the static files to. 
StaticFileOptions clientAppDist = new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(
Directory.GetCurrentDirectory(),
@"ClientAppdist"
)
)
};
// Each map its own static files otherwise
// it will only ever serve index.html no matter the filename 
client.UseSpaStaticFiles(clientAppDist);
// Each map will call its own UseSpa where
// we give its own sourcepath
client.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
spa.Options.DefaultPageStaticFileOptions = clientAppDist;
});
});

您可以通过注释掉开发代码并在运行C#代码之前在各自的clientapp文件夹中运行npm-run-build来测试生产设置。只需确保生成的dist文件夹没有签入到您的git repo中即可。

希望您现在能够更好地了解它在开发环境中是如何工作的,创建构建指令,以及它将如何在生产环境中运行。

最新更新