通过WebApi下载文件返回JSON



我使用的是Visual Studio 2019,WebApi项目,.NET Core 3.1

我的端点如下:

[HttpGet("GetFile")]
public async Task<HttpResponseMessage> GetFile([FromQuery] string filePath)
{
var bytes = await System.IO.File.ReadAllBytesAsync(filePath).ConfigureAwait(false);
using var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(bytes),
};
result.Content.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment")
{
FileName = Path.GetFileName(filePath),
};
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
return result;
}

当我到达URL时,它会以JSON形式返回序列化的HttpResponseMessage
如何从端点下载文件?

为了简化,您可以使用以下内容:

public async Task<IActionResult> GetFile([FromQuery] string filePath)
{
var bytes = await System.IO.File.ReadAllBytesAsync(filePath).ConfigureAwait(false);
return File(bytes, "application/octet-stream", Path.GetFileName(filePath));
}

最新更新