启动后添加新的 FileServer 位置(启动后编辑中间件)

Add new FileServer locations after startup (edit middleware after startup)

我的网络应用程序需要让管理员用户在 .net core 2 应用程序中添加和删除提供的文件夹。我找到了一种提供服务文件夹列表的方法,但是我找不到在配置应用程序后动态添加或删除它们的方法。

如何从应用程序中重新运行 配置功能?或者,如何在已经 运行ning 的服务中添加或删除 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。

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

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

您必须将上述存储库中的 MiddlewareInjectorOptionsMiddlewareInjectorMiddlewareMiddlewareInjectorExtensions class 添加到您的项目中。

然后,在您的 Startup class 中,将 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