在ConfigureServices(aspnetcore)中获取wwwroot路径

Qur*_*tor 5 c# asp.net-core

在我的aspnetcore应用(v2.1)中,我需要配置一个〜/ wwwroot / App_Data / quranx.db中的只读数据库(entityframework核心+ SQLite)

我需要在Startup.ConfigureServices中调用此代码

services.AddDbContext<QuranXDataContext>(options => options
    .UseSqlite($"Data Source={databasePath}")
    .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)
);
Run Code Online (Sandbox Code Playgroud)

但是到那时,我无法找到通往wwwroot的途径。要获得该路径,我需要IHostingEnvironment,但是直到Startup.Configure调用完成,即Startup.ConfigureServices完成后,我才能获得对该路径的引用。

怎么做?

Kir*_*kin 7

这是很容易访问IHostingEnvironmentConfigureServices(我已经解释了如何下文),但你读的细节之前,先来看看克里斯·普拉特在评论中警告有关如何wwwroot中存储数据库是一个非常糟糕的主意。


您可以IHostingEnviromentStartup类中采用类型的构造函数参数,并将其捕获为字段,然后可以在其中使用ConfigureServices

public class Startup
{
    private readonly IHostingEnvironment _env;

    public Startup(IHostingEnvironment env)
    {
        _env = env;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        // Use _env.WebRootPath here.
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

对于ASP.NET Core 3.0+,请使用IWebHostEnvironment代替IHostingEnvironment

  • 虽然这在技术上回答了这个问题,但应该注意你绝对*不*在`wwwroot`下有一个数据库。那是您网站的“公共”区域,可以直接在网络上访问那里的任何内容。当然,假设目录浏览关闭,则需要知道数据库文件的确切位置,但默默无闻的安全性不是安全性。 (2认同)