ContentRoot: C:\MyApp\wwwroot
WebRoot: C:\MyApp\wwwroot\wwwroot
默认情况下 contentRoot是使用程序更目录
可以查看源代码Microsoft.AspNetCore.Hosting.WebHostBuilder 248行
var contentRootPath = ResolveContentRootPath(_options.ContentRootPath, AppContext.BaseDirectory);
private string ResolveContentRootPath(string contentRootPath, string basePath) 334行
{
if (string.IsNullOrEmpty(contentRootPath))
{
return basePath;
}
if (Path.IsPathRooted(contentRootPath))
{
return contentRootPath;
}
return Path.Combine(Path.GetFullPath(basePath), contentRootPath);
}
我们可以清楚的看到contentRootPath 就是默认程序目录 由此我们可以更改默认目录到我们物流硬盘的任何位置作为静态分布式文件的存放目录,大型的系统对于静态文件都是分开的 所以这个很好的解决了我们的物理存放文件路径的问题
在来webroot
_hostingEnvironment.Initialize(contentRootPath, _options); 251行
Microsoft.AspNetCore.Hosting.Internal.HostingEnvironmentExtensions 扩张方法就是合并2个文件路径
public static void Initialize(this IHostingEnvironment hostingEnvironment, string contentRootPath, WebHostOptions options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (string.IsNullOrEmpty(contentRootPath))
{
throw new ArgumentException("A valid non-empty content root must be provided.", nameof(contentRootPath));
}
if (!Directory.Exists(contentRootPath))
{
throw new ArgumentException($"The content root '{contentRootPath}' does not exist.", nameof(contentRootPath));
}
hostingEnvironment.ApplicationName = options.ApplicationName;
hostingEnvironment.ContentRootPath = contentRootPath;
hostingEnvironment.ContentRootFileProvider = new PhysicalFileProvider(hostingEnvironment.ContentRootPath);
var webRoot = options.WebRoot;
if (webRoot == null)
{
// Default to /wwwroot if it exists.
var wwwroot = Path.Combine(hostingEnvironment.ContentRootPath, "wwwroot");
if (Directory.Exists(wwwroot))
{
hostingEnvironment.WebRootPath = wwwroot;
}
}
else
{
hostingEnvironment.WebRootPath = Path.Combine(hostingEnvironment.ContentRootPath, webRoot);
}
if (!string.IsNullOrEmpty(hostingEnvironment.WebRootPath))
{
hostingEnvironment.WebRootPath = Path.GetFullPath(hostingEnvironment.WebRootPath);
if (!Directory.Exists(hostingEnvironment.WebRootPath))
{
Directory.CreateDirectory(hostingEnvironment.WebRootPath);
}
hostingEnvironment.WebRootFileProvider = new PhysicalFileProvider(hostingEnvironment.WebRootPath);
}
else
{
hostingEnvironment.WebRootFileProvider = new NullFileProvider();
}
hostingEnvironment.EnvironmentName =
options.Environment ??
hostingEnvironment.EnvironmentName;
}
最终的webRoot 就是在这里创建的
那么如何更改WebRoot和ContentRoot 有2中方式一个是配置文件appsettings.json key值contentRoot , webroot
一个是启动文件修改
Microsoft.AspNetCore.Hosting.HostingAbstractionsWebHostBuilderExtensions
此类包含了IWebHostBuilder 默认扩展
UseContentRoot
UseWebRoot
以上2个方法就是我们在启动的时候可以修改路径的方法都是调用的最终这个方法吧值设置到IConfiguration中 如果是配置文件默认就配置了
public IWebHostBuilder UseSetting(string key, string value)
{
_config[key] = value;
return this;
}