我在一个小项目中有一个 Startup.cs 文件,用于托管 Kestrel 静态文件的 Web服务器:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new RequireHttpsAttribute());
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
var configBuilder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("config.json");
var config = configBuilder.Build();
var options = new RewriteOptions()
.AddRedirectToHttps();
app.UseRewriter(options);
DefaultFilesOptions defoptions = new DefaultFilesOptions();
defoptions.DefaultFileNames.Clear();
defoptions.DefaultFileNames.Add("index.html");
app.UseDefaultFiles(defoptions);
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"static")),
RequestPath = new PathString("")
});
loggerFactory.AddConsole(config.GetSection(key: "Logging"));
}
}
但是,它不会尝试加载索引.html或任何东西。如果我手动访问它,它确实有效。
有什么想法吗?
谢谢
理想情况下,您的index.html
应该在 Web 根路径 ( wwwroot
下 (,但是,如果您的文件在 ContentRootPathstatic
下(看起来如此(,则需要更改代码以指定DefaultFilesOptions.FileProvider
,如下所示:
PhysicalFileProvider fileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), @"static"));
DefaultFilesOptions defoptions = new DefaultFilesOptions();
defoptions.DefaultFileNames.Clear();
defoptions.FileProvider = fileProvider;
defoptions.DefaultFileNames.Add("index.html");
app.UseDefaultFiles(defoptions);
app.UseStaticFiles();
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = fileProvider,
RequestPath = new PathString("")
});
注意:您可能最好使用IHostingEnvironment.ContentRootPath
(env.ContentRootPath
(而不是Directory.GetCurrentDirectory()
第一行(以防万一您想在某个时候更改WebHostBuilder
中的内容根目录(。
CalC的洞察力,这使我更接近 asp.net 核心2.2的答案。以下是我最终需要执行的操作,以便在 Azure 中的主 Web 服务器根目录之外提供默认文档:
public void Configure(IApplicationBuilder app){...
// content is physically stored at /site/abc on an Azure Web App, not /site/wwwroot/abc
string path = Path.Combine(Directory.GetCurrentDirectory(), "abc");
PhysicalFileProvider fileProvider = new PhysicalFileProvider(path);
DefaultFilesOptions options = new DefaultFilesOptions
{
FileProvider = fileProvider,
RequestPath = "/ABC",
};
options.DefaultFileNames.Add("index.html");
app.UseDefaultFiles(options);
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = fileProvider,
RequestPath = "/ABC"
});
}
键正在使用匹配的 RequestPath 和 FileProvider 值