简体   繁体   English

有没有办法从 ASP.NET Core IFileProvider 类中检索 HttpContext?

[英]Is there a way to retrieve HttpContext from ASP.NET Core IFileProvider class?

I am trying to get the instance of HttpContext from the IFileProvider , so I can access the original path requested before the route mapping updated in the subpath.我正在尝试从IFileProvider获取HttpContext的实例,因此我可以访问在子路径中更新路由映射之前请求的原始路径。

I am trying out a sample to read view dynamically from a database, but as the path is always mapped to the main controller, and the views cached I can't get access to the original request path to load the correct view from the database.我正在尝试从数据库动态读取视图的示例,但由于路径始终映射到主控制器,并且视图缓存,我无法访问原始请求路径以从数据库加载正确的视图。 The only way I could make it work is to hardcore the mappings and have respectively different controller or actions handling each file, but then it won't be using the dynamic views from the database.我可以让它工作的唯一方法是对映射进行硬核,并分别使用不同的控制器或操作来处理每个文件,但它不会使用来自数据库的动态视图。

public class DBViewProvider : IFileProvider {

    public IDirectoryContents GetDirectoryContents(string subpath) {
        string path = ConvertPath(subpath);

        return new DBViewDirectoryContents(path);
    }

The dependency injection will help you inject the HttpContextAccessor in the constructor依赖注入将帮助您在构造函数中注入HttpContextAccessor

public class DBViewProvider : IFileProvider {
 private readonly IHttpContextAccessor httpContextAccessor;

 public DBViewProvider(IHttpContextAccessor httpContextAccessor){
     this.httpContextAccessor = httpContextAccessor;
 }
 
 public IDirectoryContents GetDirectoryContents(string subpath) {
    HttpContext httpContext = httpContextAccessor.HttpContext;

    string path = ConvertPath(subpath);

    return new DBViewDirectoryContents(path);
 }

 /*******************hidden for brievety************/
}

You will need to add this line in the Startup.ConfigureServices method like this您需要像这样在Startup.ConfigureServices方法中添加这一行

services.AddHttpContextAccessor();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM