通过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));
}