Search code examples
c#asp.net-corekestrel

app.UseDefaultFiles in Kestrel not doing anything?


I have this in a Startup.cs file for a small project for a webserver hosting static files with Kestrel:

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"));
    }
}

However, it doesn't try to load an index.html or anything. If I access it manually, it does indeed work.

Any ideas?

Thanks


Solution

  • Ideally your index.html should be under the web root path (wwwroot), however, if your file is under ContentRootPath\static (as it appears to be), you will need to change your code to specify the DefaultFilesOptions.FileProvider as follows:

    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("")
    });
    

    Note: you are probably better off using IHostingEnvironment.ContentRootPath (env.ContentRootPath) rather than Directory.GetCurrentDirectory() on the first line (just in case you want to change the content root in your WebHostBuilder at some point).