【问题标题】:dotnet core UseStaticFiles index fallbackdotnet core UseStaticFiles 索引回退
【发布时间】: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 中进行配置,所以这一切都在同一个地方。

【问题讨论】:

    标签: .net-core static-files


    【解决方案1】:

    我最终编写了一个执行索引回退的文件提供程序。它封装了一个PhysicalFileProvider,如果找不到文件,则在一定条件下返回index.html。在我的情况下,条件基于文件夹 css、img 或 js。

    它是这样实现的:

    using Microsoft.Extensions.FileProviders;
    using Microsoft.Extensions.Primitives;
    using System.Linq;
    
    public class IndexFallbackFileProvider : IFileProvider
    {
       private readonly PhysicalFileProvider _innerProvider;
    
       public IndexFallbackFileProvider(PhysicalFileProvider physicalFileProvider)
       {
          _innerProvider = physicalFileProvider;    
       }
    
       public IDirectoryContents GetDirectoryContents(string subpath)
       {
          return _innerProvider.GetDirectoryContents(subpath);
       }
    
       public IFileInfo GetFileInfo(string subpath)
       {
          var fileInfo = _innerProvider.GetFileInfo(subpath);
          if(!fileInfo.Exists && MustFallbackToIndex(subpath))
          {
             if(!_staticFilesFolders.Any(f => subpath.Contains(f)))
             {
                fileInfo = _innerProvider.GetFileInfo("/index.html");
             }         
          }
    
          return fileInfo;
       }
    
       // Plain 404 are OK for css, img, js.
       private static string[] _staticFilesFolders = new string[] { "/css/", "/img/", "/js/" };
       private static bool MustFallbackToIndex(string subpath)
       {
          return !_staticFilesFolders.Any(f => subpath.Contains(f));
       }
    
       public IChangeToken Watch(string filter)
       {
          return _innerProvider.Watch(filter);
       }
    }
    

    然后,在 startup.config 中,我使用此提供程序。 另外,我必须将ServeUnknownFileTypes 设置为true 才能响应对/path/without/extension 的请求。

    var physicalFileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "wwwroot"));
    var fileProvider = new IndexFallbackFileProvider(physicalFileProvider);
    
    var staticFileOptions = new StaticFileOptions
    {
       FileProvider = fileProvider,
       ServeUnknownFileTypes = true
    };
    
    app.UseStaticFiles(staticFileOptions);
    

    【讨论】:

      猜你喜欢
      • 2019-12-02
      • 1970-01-01
      • 2016-09-10
      • 1970-01-01
      • 2017-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多