2017-08-16 56 views
3

我的web应用程序需要让管理员用户从.net core 2应用程序添加和删除服务的文件夹。我找到了一种提供服务文件夹列表的方法,但是我找不到一种方法来在应用程序配置后动态地添加或删除它们。启动后添加新的FileServer位置(启动后编辑中间件)

如何从应用程序中重新运行配置功能?或者,如何在已经运行的服务中添加或删除UseFileServer()配置?

public class Startup 
{ 
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
    { 
     app.UseDeveloperExceptionPage(); 
     app.UseMvc(); 

     //get these dynamically from the database 
     var locations = new Dictionary<string, string>{ 
      {@"C:\folder1", "/folder1"}, 
      {@"D:\folder2", "/folder2"} 
     }; 
     foreach (var kvp in locations) 
     { 
      app.UseFileServer(new FileServerOptions() 
      { 
       FileProvider = new PhysicalFileProvider(
        kvp.Key 
       ), 
       RequestPath = new PathString(kvp.Value), 
       EnableDirectoryBrowsing = true 
      }); 
     } 
    } 
} 

我正在使用.net core 2.0.0-preview2-final。

回答

2

您可能希望根据您的设置动态注入FileServer中间件。

有微软的Chris Ross的Github上的示例项目:https://github.com/Tratcher/MiddlewareInjector/tree/master/MiddlewareInjector

你必须从上述回购加MiddlewareInjectorOptionsMiddlewareInjectorMiddlewareMiddlewareInjectorExtensions类项目。

然后,在你的启动类,登记MiddlewareInjectorOptions为单(所以它在整个应用程序可用),并使用MiddlewareInjector:

public class Startup 
{ 
    public void ConfigureServices(IServiceCollection serviceCollection) 
    { 
     serviceCollection.AddSingleton<MiddlewareInjectorOptions>(); 
    } 

    public void Configure(IApplicationBuilder app, IHostingEnvironment env) 
    { 
     app.UseDeveloperExceptionPage(); 

     var injectorOptions = app.ApplicationServices.GetService<MiddlewareInjectorOptions>(); 
     app.UseMiddlewareInjector(injectorOptions); 
     app.UseWelcomePage(); 
    } 
} 

然后,注入无论你想在MiddlewareInjectorOptions和动态配置中间件,像这样:

public class FileServerConfigurator 
{ 
    private readonly MiddlewareInjectorOptions middlewareInjectorOptions; 

    public FileServerConfigurator(MiddlewareInjectorOptions middlewareInjectorOptions) 
    { 
     this.middlewareInjectorOptions = middlewareInjectorOptions; 
    } 

    public void SetPath(string requestPath, string physicalPath) 
    { 
     var fileProvider = new PhysicalFileProvider(physicalPath); 

     middlewareInjectorOptions.InjectMiddleware(app => 
     { 
      app.UseFileServer(new FileServerOptions 
      { 
       RequestPath = requestPath, 
       FileProvider = fileProvider, 
       EnableDirectoryBrowsing = true 
      }); 
     }); 
    } 
} 

注意,这MiddlewareInjector可以注入只是一个单一的中间件,让您的代码应该调用UseFileServer()你要投放的每个路径。

我已经创建了所需的代码要点:https://gist.github.com/michaldudak/4eb6b0b26405543cff4c4f01a51ea869

+0

这并没有解决我的问题。我需要在启动完成后注册新的UseFileServer位置。我测试了它,一旦应用程序正在运行,任何新的app.UseFileServer调用都不会执行任何操作。 – TwitchBronBron

+0

然后,我的解决方案应该可以工作。既然你有一个单件MiddlewareInjectorOptions,你可以随时使用它(只需从服务容器中获取它)。我前一段时间测试了它,它似乎工作正常。 –

+0

请看看我刚添加的Gist - 起初,没有文件服务器功能。只有当您启用/启用文件服务器URL时,才能通过分别转到/ c和/ d URL来访问C和D驱动器的内容。 –