2017-11-17 7 views
1

Ich habe dies in einer Startup.cs Datei für ein kleines Projekt für ein Webserver-Hosting-statische Dateien mit Kestrel:app.UseDefaultFiles in Kestrel macht nichts?

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

Es ist jedoch nicht einem index.html oder irgendetwas zu laden nicht versuchen. Wenn ich manuell darauf zugreife, funktioniert es tatsächlich.

Irgendwelche Ideen?

Dank

+1

Was ist der Pfad zu Ihrer index.html Datei - ist es unter wwwroot? – CalC

Antwort

2

Idealer Ihre index.html sollte unter der Web-Root-Pfad (wwwroot) sein, aber wenn Sie Ihre Datei unter ContentRootPath\static (wie es scheint), müssen Sie den Code ändern, um die DefaultFilesOptions.FileProvider angeben wie folgt:

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

Hinweis: sind Sie wahrscheinlich besser dran mit IHostingEnvironment.ContentRootPath (env.ContentRootPath) statt Directory.GetCurrentDirectory() in der ersten Zeile (für den Fall, Sie wollen c hange den Inhalt root in deinem WebHostBuilder an irgendeinem Punkt).

+1

Vielen Dank, funktioniert perfekt. Ich habe nicht herausgefunden, dass ich auch FileProvider mit DefaultFilesOptions verwenden musste (-_-) –