在ConfigureServices(aspnetcore)中获取wwwroot路径 [英] Get wwwroot path when in ConfigureServices (aspnetcore)

查看:79
本文介绍了在ConfigureServices(aspnetcore)中获取wwwroot路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my aspnetcore app (v2.1) I need to configure a read-only database (entityframework core + SQLite) which is in ~/wwwroot/App_Data/quranx.db

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

I need to call this code in Startup.ConfigureServices

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

但是到那时,我找不到找到wwwroot路径的方法.要获得该路径,我需要 IHostingEnvironment ,但是直到调用 Startup.Configure 且在 Startup.ConfigureServices <之后,我才能获得对此的引用./code>完成.

But at that point I cannot find a way to get the path to wwwroot. To get that path I need IHostingEnvironment, but I am unable to get a reference to that until Startup.Configure is called, and that is after Startup.ConfigureServices has finished.

这是怎么做的?

推荐答案

ConfigureServices 中访问 IHostingEnvironment 很容易(我已经在下面说明了),但是在您之前阅读详细信息,并在评论Chris Pratt的警告中了解有关如何在wwwroot中存储数据库是一个非常坏主意.

It's easy enough to access IHostingEnvironment in ConfigureServices (I've explained how below) but before you read the specifics, take a look at Chris Pratt's warning in the comments about how storing a database in wwwroot is a very bad idea.

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

You can take a constructor parameter of type IHostingEnviroment in your Startup class and capture that as a field, which you can then use in 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 .

For ASP.NET Core 3.0+, use IWebHostEnvironment instead of IHostingEnvironment.

这篇关于在ConfigureServices(aspnetcore)中获取wwwroot路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆