.NET Core API - Return 图片 URL 来自服务器而非本地存储

.NET Core API - Return Image URL from Server and not from local storage

在 Chrome 中出现以下错误:

Not allowed to load local resource: C://...

现在我想更改 return 中的图像 '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);