始终从IWebHostEnvironment和IHttpContextAccessor获取null值



我正在尝试上传文件。但是IWebHostEnvironment和IHttpContextAccessor总是返回null值。这是控制器的一部分。

private readonly IUnitOfWork _unitOfWork;
private readonly IWebHostEnvironment _webHostEnvironment;
private readonly IHttpContextAccessor _httpContextAccessor;
[HttpPost]
public async Task<ActionResult<LS>> PostStApp(StApp stapp)
{
var url = _httpContextAccessor.HttpContext.Request.Host.Value;
var path = $"{_webHostEnvironment.WebRootPath}\upload\{stapp.ImageName}";
var fileStream = System.IO.File.Create(path);
fileStream.Write(stapp.Image, 0, stapp.Image.Length);
fileStream.Close();
stapp.ImageName = $"https://{url}/upload/{stapp.ImageName}";
await _unitOfWork.StApp.Insert(stapp);
await _unitOfWork.Save(HttpContext);
return CreatedAtAction("GetStApp", new { id = stapp.Id }, stapp);
}

url和路径始终为null。我错过什么了吗?

确保通过如下构造函数注入两个服务的依赖关系:

private readonly IWebHostEnvironment _webHostEnvironment;
private readonly IHttpContextAccessor _httpContextAccessor;
public HomeController(IWebHostEnvironment webHostEnvironment, IHttpContextAccessor httpContextAccessor)
{
_webHostEnvironment = webHostEnvironment;
_httpContextAccessor = httpContextAccessor;
}

我忘记了依赖注入这两个服务。这是在将其放入控制器后工作的。。

public SAppController(IUnitOfWork unitOfWork, IWebHostEnvironment webHostEnvironment, IHttpContextAccessor httpContextAccessor)
{
_unitOfWork = unitOfWork;
this._webHostEnvironment = webHostEnvironment;
this._httpContextAccessor = httpContextAccessor;
}

相关内容

  • 没有找到相关文章

最新更新