我现在有这项工作,而且工作很辛苦。
关键是环境信息“ContentRootPath”,在您的示例中将返回 MySolution\src\MyProject
的路径
我的测试应用是下面的“数据库优先”教程
https://docs.efproject.net/en/latest/platforms/aspnetcore/existing-db.html
进行了一些更改,以适应我教授网络应用程序编程的情况,并需要我和学生可以在彼此的机器上运行以进行讨论、标记等的自包含应用程序。
在 appsettings.json 中
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;AttachDBFilename=%CONTENTROOTPATH%\\App_Data\\blogging.mdf;Trusted_Connection=true;MultipleActiveResultSets=true"
}
与众不同的部分是:
AttachDBFilename=%CONTENTROOTPATH%\\App_Data\\blogging.mdf
好的,我使用的是传统名称“App_Data”,但它在 ContentRootPath 下比在“wwwroot”下更安全。
然后在 Startup.cs 中
public class Startup
{
//20160718 JPC enable portable dev database
private string _contentRootPath = "";
public Startup(IHostingEnvironment env)
{
//20160718 JPC enable portable dev database
_contentRootPath = env.ContentRootPath;
...
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//20160718 JPC enable portable dev database
string conn = Configuration.GetConnectionString("DefaultConnection");
if(conn.Contains("%CONTENTROOTPATH%"))
{
conn = conn.Replace("%CONTENTROOTPATH%", _contentRootPath);
}
...
}
上面的“...”代表Visual Studio 2015生成的标准代码。
请注意,当我们“发布”这样的应用程序时,我们需要手动将自定义文件夹和文件(例如我的“App_Data”文件夹)复制并粘贴到发布的版本中。或者我们可以将自定义文件夹名称(在本例中为“App_Data”)添加到文件“project.json”中。
还很高兴知道,对于包括控制器类在内的任何类,我们都可以添加一个带参数 env 的构造函数方法,并且托管环境将为我们提供有用的信息,包括 ContentRootPath。用于自定义文件存储,例如为我们的用户提供文件上传。
public class HomeController : Controller
{
//20160719 JPC access hosting environment via controller constructors
private IHostingEnvironment _env;
public HomeController(IHostingEnvironment env)
{
_env = env;
}
public IActionResult Index()
{
string contentRootPath = _env.ContentRootPath;
return View();
}
好的,这只是为了演示原理,因为我在“return View()”上添加了一个断点,然后将鼠标悬停在 contentRootPath 上以说明这一点。
ASP.NET Core MVC6 看起来像是我遇到的更大的学习和教学挑战之一。祝我们所有人好运。我发现了一个不错的进步:在 MVC5 中,我们有一些戏剧性的事情,让我们的自定义数据和身份 AspNetUser 表在一个数据库中很好地结合在一起。看起来它在 MVC6 中是一个更整洁的命题。