问题
I have the following asp.net core spa application configured (react-redux template)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UsePathBase(new PathString("/foo"));
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
}
I’d like to set pathBase for application, but app.UsePathBase(new PathString("/foo"))
just ignored. On 2.2 it perfectly worked. Automatically modified index.html and all static files were moved to relative path. But on 3.0 (3.1) static + generated files are placed on root.
Generated files on .Net Core 2.2
Generated files on .Net Core 3.0
Does anyone have any ideas for solving it? Or may be some examples of Startup.cs with working pathBase?
回答1:
Usually,
app.UsePathBase(new PathString("/foo"));
is used because the reverse proxy cuts off some prefix and causes ASP.NET Core app doesn't realize the virtual app path is start with/foo
. In your scenario, if you don't have a reverse proxy that rewrite the prefix to empty string, you don't needapp.UsePathBase(...)
.Instead, if you your spa runs on a subpath, you could setup a middleware that branches the
/foo
.- Finally, you might want to add a property of
homepage
in yourpackage.json
so that it will generate the<base url="/foo/"/>
when publishing. Or as an alternative, you could update the<base url="">
inClientApp/public/index.html
manually.
In short, add a "homepage": "/foo/"
in your package.json
"private": true, "homepage": "/foo/", "dependencies": { ... }
And setup a /foo
branch to make SPA runs under that path:
string spaPath = "/foo";
app.Map(spaPath,appBuilder =>{
appBuilder.UseSpa(spa =>
{
spa.Options.DefaultPage = spaPath+"/index.html";
spa.Options.DefaultPageStaticFileOptions = new StaticFileOptions{
RequestPath = spaPath,
};
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
});
Don't use app.UsePathBase(new PathString("/foo"))
unless you understand you do want to override the path base for all routes.
来源:https://stackoverflow.com/questions/60189339/asp-net-core-3-0-3-1-set-pathbase-for-single-page-application