【发布时间】:2021-03-24 04:03:20
【问题描述】:
Net Core 网络应用程序,具有用户可以上传照片的实用程序。它使用 API 控制器进行实际上传。我在解决方案中创建了一个名为 ImageStorage 的文件夹,其中文件夹路径如下所示:
G:\GameDevelopment\DungeonMaxer\MainApp\wwwroot\ImageStorage
我还在 ImageStorage 下创建了一个名为 uploads 的文件夹。
我正在尝试在本地(IIS Express)进行测试,并将这一行添加到控制器中:
[HttpPost("upload")]
public async Task<IActionResult> PostAsync(IFormFile file)
{
// parent folder for storage
var serverStoragePath = Server.MapPath(@"~/ImageStorage");
// uploads folder inside the parent
var fileRoute = Path.Combine(serverStoragePath, "uploads");
// get file extension
string extension = System.IO.Path.GetExtension(theFile.FileName);
// create a new name for storage
string name = Guid.NewGuid().ToString().Substring(0, 8) + extension;
// get the link to the file
string link = Path.Combine(fileRoute, name);
using (FileStream writerFileStream = System.IO.File.Create(link))
{
await stream.CopyToAsync(writerFileStream);
writerFileStream.Dispose();
}
// Return the file path as json
Hashtable imageUrl = new Hashtable();
imageUrl.Add("link", "/uploads/" + name);
return Json(imageUrl);
}
但是当我在本地运行项目并在var serverStoragePath = Server.MapPath(@"~/ImageStorage");这一行上放一个断点时,我得到了这个错误:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
我也尝试了wwwroot\ImageStorage,但这给了我同样的错误。
有没有办法访问这个路径?
谢谢!
【问题讨论】:
-
会不会只是权限问题?我假设您已经使用调试器检查了最终文件名是否正确。
-
@Steve 我知道路径存在于我的文件系统中。我还在 Microsoft 网站上查找了 Server.MapPath,我认为我使用它是正确的。
-
调用 Server.MapPath 后 serverStoragePath 的值是多少?...这也可能不是应用程序基本路径设置为的位置
-
等等。您是否尝试在 Asp.Net Core 项目中使用 Server.MapPath?没办法,需要通过DI使用IWebHostEnvironment,然后使用属性WebRootPath
-
Just Path.Combine WebRootPath 与您的文件夹/s
标签: c# asp.net-core asp.net-core-webapi