[英]IEnvironment.WebRootPath and Virtual Directory in IIS
我在IIS 7.5中拥有一个网站,试图将文件上传到位于另一个驱动器上的Files文件夹中。 我将名为文件的虚拟文件夹添加到wwwroot文件夹中。
该虚拟文件文件夹路径为D:\\ files
我在Controller中上传的代码:
_env变量为IHostingEnvironment,并注入到Constructor中。
var filename = _env.WebRootPath + $@"\files\{model.JobID}.{model.FileExt}";
using (FileStream fs = System.IO.File.Create(filename))
{
AttachFile.CopyTo(fs);
fs.Flush();
}
它在本地工作,因为我的机器中有物理文件夹wwwroot \\ files。 但是它在生产服务器上不起作用,并出现以下错误:
An unhandled exception has occurred: Could not find a part of the path 'C:\inetpub\Mysite\wwwroot\files\111214.png'.
但是我在ASPNet 4.6.1中拥有另一个网站,并且我使用Server.MapPath来上传文件。 它可以在该网站上运行,并且我可以成功上传文件。
string SaveLocation = string.Format(@"{0}\{1}{2}", Server.MapPath("files"), JobID, FileExt);
根据这篇文章,它说Server.MapPath和WebRootPath是相似的。 http://www.mikesdotnetting.com/article/302/server-mappath-equivalent-in-asp-net-core
但是,在我看来,WebRootPath仅为我们提供了网站的RootPath。 它不接受参数来评估给定的URL,例如Server.MapPath。
您能否建议我如何在Production Server上上传文件,而不是对.Net Core应用程序中的物理路径进行硬编码?
更新1:
这是迄今为止我所能达到的最好成绩。我们可以通过这种方式访问或创建另一个虚拟URL来指向另一个位置。 可以通过http://mysite/Files/abc.jpg访问
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(@"D:\Files"),
RequestPath = new PathString("/Files"),
});
但是,它只是只读的url,我无法使用“ /Files/newfile.jpg”或Path.Combine(_env.WebRootPath,“ newfile.jpg”)上载到此路径,因为它实际上并不存在。
这是配置内容和Web根目录的方法:
public class Program
{
public static void Main(string[] args)
{
var contentRoot = Directory.GetCurrentDirectory();
var config = new ConfigurationBuilder()
.SetBasePath(contentRoot)
.AddJsonFile("hosting.json", optional: true)
.Build();
//WebHostBuilder is required to build the server. We are configurion all of the properties on it
var hostBuilder = new WebHostBuilder()
.UseKestrel()
//Content root - in this example it will be our current directory
.UseContentRoot(contentRoot)
//Web root - by the default it's wwwroot but here is the place where you can change it
//.UseWebRoot("wwwroot")
//Startup
.UseStartup<Startup>()
.UseConfiguration(config);
var host = hostBuilder.Build();
//Let's start listening for requests
host.Run();
}
}
您可能正在寻找UseWebRoot()和UseContentRoot()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.