在 Chrome 中,我收到以下错误:
Not allowed to load local resource: C://...
现在我想改变图像的返回,比如'localhost:44346/wwwroot/images/profileimages/img.jpg'
你能告诉我我该怎么做吗?
这是我的文件上传控制器:
[HttpPut]
[Authorize]
[RequestSizeLimit(1_000_000)]
[Route("UpdateImage")]
public async Task<IActionResult> UpdateImage([FromForm]ApplicationUserModel model)
{
try
{
var user = await _userManager.FindByIdAsync(model.id);
if (user.ProfileImagePath != null)
{
var file = new FileInfo(user.ProfileImagePath);
file.Delete();
}
var uniqueFileName = GetUniqueFileName(model.ProfileImage.FileName);
var uploads = Path.Combine(hostingEnvironment.WebRootPath, "Images\\ProfileImages");
var filePath = Path.Combine(uploads, uniqueFileName);
await model.ProfileImage.CopyToAsync(new FileStream(filePath, FileMode.Create));
user.ProfileImagePath = filePath;
var result = await _userManager.UpdateAsync(user);
return Ok(result);
}
catch (Exception ex)
{
throw ex;
}
}
这是用于获取用户信息的控制器:
[HttpGet]
[Authorize]
[Route("GetCurrentUser")]
public async Task<IActionResult> GetCurrentUser()
{
try
{
var userId = User.FindFirst("UserID")?.Value;
var data = await _userManager.FindByIdAsync(userId);
var user = new UserStandardModel
{
id = userId,
LastName = data.LastName,
FirstName = data.FirstName,
ProfileImagePath = data.ProfileImagePath
};
return Ok(user);
}
catch (Exception ex)
{
throw ex;
}
}
所以我找到了解决我的问题的方法。当我触发 GetCurrentUser 函数时,我会检查 FilePath 是否以“C”开头。如果这是真的,我将使用我的本地主机地址格式化文件路径。就像布鲁诺建议的那样。
但这只有在我的 Startup.cs 中有 UseStaticFiles() 时才有效
app.UseStaticFiles();
这并不漂亮,但它可以完成工作并且仅用于测试。
var userId = User.FindFirst("UserID")?.Value;
var data = await _userManager.FindByIdAsync(userId);
var user = new UserStandardModel
{
id = userId,
LastName = data.LastName,
FirstName = data.FirstName,
ProfileImagePath = data.ProfileImagePath
};
if (user.ProfileImagePath.StartsWith('C'))
{
var url = "https://localhost:44356/";
user.ProfileImagePath = user.ProfileImagePath.Remove(0,58);
user.ProfileImagePath = url + user.ProfileImagePath;
}
return Ok(user);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句