c# - 上传 0 字节图像 - C# .NET Core 和异步问题
问题描述
我已经看到这个问题出现在其他问题上,请相信我,我尝试了很多事情来让它工作。当我处于调试模式时,我可以上传图像并让它完美显示,但是一旦它投入生产,我得到的只是空白的 0 字节图像。我尝试使整个任务异步,包括等待命令,重置流位置,并尝试了 Azure blob 容器。我究竟做错了什么?Web 应用程序托管在 Azure 上。
控制器,类别控制器.cs
[Route("save")]
[HttpPost]
public async Task<IActionResult> Save(SaleItem item, IFormFile photo)
{
if (item.AccessValidation == 000)
{
if (photo == null || photo.Length == 0)
{
item.ImgURL = string.Empty;
}
else
{
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/data/images", photo.FileName);
var stream = new FileStream(path, FileMode.Create);
await photo.CopyToAsync(stream).ConfigureAwait(true);
stream.Seek(0, SeekOrigin.Begin);
stream.Close();
item.ImgURL = photo.FileName;
}
item.AccessValidation = 1;
WriteXML(item);
return View("Success");
}
else
{
return Content("Invalid item submission!");
}
}
查看,Post.cshtml
<form asp-action="save" method="post" enctype="multipart/form-data">
<div class="grid-x grid-padding-x">
<div class="cell large-8">
<label>Item Description</label>
<input type="text" id="itemDescription" asp-for="Description" />
</div>
<div class="cell large-4">
<input type="submit" class="button large right" value="Save to Inventory" />
</div>
</div>
这个问题得到了回答 - 如果有人在未来查看这个并想知道我是如何实现它的,这就是我需要更改的内容: Controller, CategoriesController.cs
using Microsoft.AspNetCore.Hosting; //add this reference
namespace Home.Move.Inventory.Controllers
{
public class CategoriesController : Controller
{
private readonly IWebHostEnvironment _env;
public CategoriesController(IWebHostEnvironment env)
{
_env = env;
}
[Route("save")]
[HttpPost]
public async Task<IActionResult> Save(SaleItem item, IFormFile photo)
{
if (item.AccessValidation == 0000)
{
if (photo == null || photo.Length == 0)
{
item.ImgURL = string.Empty;
}
else
{
var path = Path.Combine(_env.ContentRootPath, "wwwroot/data/images", photo.FileName);
var stream = new FileStream(path, FileMode.Create);
await photo.CopyToAsync(stream).ConfigureAwait(true);
stream.Seek(0, SeekOrigin.Begin);
stream.Close();
item.ImgURL = photo.FileName;
}
item.AccessValidation = 1;
WriteXML(item);
return View("Success");
}
else
{
return Content("Invalid item submission!");
}
}
}
我还必须更新对 contentrootpath 的其他引用——我认为我在某些领域使用它,但在其他领域没有使用它,主要是由于缺乏经验。我的理解是,我在这里所做的是依赖注入,并且在整个课程中始终将其用作 _env 是有意义的。
解决方案
我认为问题出在你的路径上。
Directory.GetCurrentDirectory()将在本地工作,但大多数用户都面临生产问题。
使用environment.ContentRootPath 代替 Directory.GetCurrentDirectory()
为了使 Directory.GetCurrentDirectory() 工作,我们需要将整个 w3wp.exe 进程的当前工作设置为您的应用程序目录。更改当前目录后,如果 IIS 尝试延迟加载模块或另一个 IIS 模块依赖于当前工作目录 C:\Windows\System32\inetsrv,则将开始失败,这可能会或可能无法恢复。
我们托管 ANCM In-Process 的方式类似于 System.Web(在 w3wp 进程内部)。System.Web 也有 Directory.GetCurrentDirectory() 作为 C:\Windows\System32\inetsrv。
作为一种解决方法,我们将 ContentRoot 设置为 Configuration 中的应用程序目录。在任何可以解析 IConfiguration 的地方,都可以使用 IConfiguration[HostDefaults.ContentRootKey] 来获取应用程序目录。