在我的 aspnetcore 应用程序(v2.1)中,我需要配置一个只读数据库(entityframework core + SQLite),位于 ~/wwwroot/App_Data/quranx.db
我需要在Startup.ConfigureServices中调用这段代码
services.AddDbContext<QuranXDataContext>(options => options
.UseSqlite($"Data Source={databasePath}")
.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)
);
但那时我找不到一种方法来获取 wwwroot 的路径。为了获得该路径,我需要
IHostingEnvironment
,但在调用 Startup.Configure
之前我无法获得对该路径的引用,而那是在 Startup.ConfigureServices
完成之后。
这是如何做到的?
在
IHostingEnvironment
中访问 ConfigureServices
非常容易(我已经在下面解释了如何操作),但在阅读具体内容之前,请先看看 Chris Pratt 在评论中关于如何在 wwwroot 中存储数据库是一个 very 的警告坏主意。
您可以在
IHostingEnviroment
类中采用 Startup
类型的构造函数参数,并将其捕获为字段,然后可以在 ConfigureServices
中使用:
public class Startup
{
private readonly IHostingEnvironment _env;
public Startup(IHostingEnvironment env)
{
_env = env;
}
public void ConfigureServices(IServiceCollection services)
{
// Use _env.WebRootPath here.
}
// ...
}
对于 ASP.NET Core 3.0+,请使用
IWebHostEnvironment
而不是 IHostingEnvironment
。
Path.GetFullPath("wwwroot");