0

我在浏览器中为显示流文件编写了这段代码:

public IActionResult GetAvatar()
{
    var id = httpContextAccessor.HttpContext.User.Identity.GetUserId<long>();
    if (id > 0)
    {
        var user = dispatchers.QueryAsync(new GetUserByIdQuery { id = id }).Result;
        if (user.Success)
        {
            return PhysicalFile(Path.Combine(this.finder.PathAvatarUserUploadFolder(), user.Result.Photo), "application/octet-stream");
        }
        return BadRequest(user.ErrorMessage);
    }
    return BadRequest("Id not valid");
}

这一行:return PhysicalFile(Path.Combine(this.finder.PathAvatarUserUploadFolder(), user.Result.Photo), "application/octet-stream");

但它有问题,因为当我在浏览器中输入 url 时,它会下载文件,它必须去下载并打开该文件。

我需要在浏览器中打开文件。我怎么解决这个问题?

4

1 回答 1

0

当您使用 Chrome 开发者工具或 Fiddler 检查响应标头时,您的Content-Disposition标头设置为什么?如果将其设置为attachment浏览器将始终下载文件。您可以将 设置Content-Dispositioninline告诉浏览器在可能的情况下显示内联内容,并在无法内联显示内容时提供下载。可以通过不同的方式设置此标头,但最简单的方法是在返回文件内容之前添加一个标头,如下所示。

Response.Headers["Content-Disposition"] = $"inline; filename={user.Result.Photo}";

return PhysicalFile(Path.Combine(this.finder.PathAvatarUserUploadFolder(), user.Result.Photo), "application/octet-stream");
于 2020-03-26T20:46:47.217 回答