【发布时间】:2021-02-23 18:28:43
【问题描述】:
我的 Startup.cs 中有这个 Configure 方法。
它做了 3 件事:
- 在 wwwroot 下提供静态文件
- 为 index.html 添加 CSP 标头
- 通过 /settings.json 路由提供参数
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
// Defaults to index.html
var defaultFilesOptions = new DefaultFilesOptions();
defaultFilesOptions.DefaultFileNames.Clear();
defaultFilesOptions.DefaultFileNames.Add("index.html");
app.UseDefaultFiles(defaultFilesOptions);
var staticFileOptions = new StaticFileOptions
{
OnPrepareResponse = ctx =>
{
// Add CSP for index.html
if (ctx.File.Name == "index.html")
{
ctx.Context.Response.Headers.Append(
"Content-Security-Policy", "default-src 'self'" // etc
);
}
}
};
app.UseStaticFiles(staticFileOptions); // wwwroot
app.UseRouting();
app.UseEndpoints(endpoints =>
{
// Settings.json endpoint
endpoints.MapGet("/settings.json", async context =>
{
string json = $@"
{{
""myConfig"": ""{_configuration["myParameter"]}""
}}";
await context.Response.WriteAsync(json);
});
});
}
}
wwwroot 下的文件其实是一个带路由的 vue.js 应用。我需要为所有不存在的请求返回index.html,以便客户端路由控制页面。
目前它返回一个 404 并且没有传入 OnPrepareResponse 钩子。
如何配置索引回退以使路由器在历史模式下工作? 我认为可以通过 web.config 中的配置来实现,但我更喜欢在 Startup.js 中进行配置,所以这一切都在同一个地方。
【问题讨论】: