通过 API .net core 在浏览器中下载 mp3 文件

Download mp3 file at browser through API .net core

试图通过我创建的 API 在浏览器中下载 mp3 文件。但不是接收 mp3 文件。我不断收到 JSON 格式的响应。我已经从 中的答案中引用了,但我仍然无法下载 mp3 文件。 有没有我忽略的错误,请帮忙?

这是我从UI

下载的方法
void DownloadRecording(RecordingHistory voicehistory)
{
      try
      {
          using (var client = new WebClient())
          {
              client.DownloadFile("https://2d489fd863a2.ngrok.io/api/download/" + voicehistory.RecordingId + ".mp3", voicehistory.RecordingId + ".mp3");
          }

      }
      catch { }
}

这是我的 api 从服务器下载 mp3 的功能

 [HttpGet("download/{recordingFile}")]
 public async Task<IActionResult> DownloadVoiceRecording(string recordingFile)
 {
      string filePath = Directory.GetCurrentDirectory() + @"\audio\Processed\" + recordingFile;
      var memory = new MemoryStream();
      using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
      {
           await stream.CopyToAsync(memory);
      }
      memory.Position = 0;
      var types = GetMimeTypes();
      var ext = Path.GetExtension(filePath).ToLowerInvariant();

      return File(filePath, types[ext], recordingFile);
      }

      private Dictionary<string, string> GetMimeTypes()
      {
          return new Dictionary<string, string>
          {
              {".mp3", "audio/mpeg"},
              {".wav","audio/wav" }
          };
      }

这是我从浏览器和 Postman 得到的响应

{
    "Version": "2.0.0.0",
    "StatusCode": 200,
    "Message": "Status 200 OK",
    "Result":"��@� ... ... /// A lot of random symbol here
}

因为return值File的第一个参数是Stream的类型,所以需要传入memory

[HttpGet("download/{recordingFile}")]
    public async Task<IActionResult> DownloadVoiceRecording(string recordingFile)
    {
        
        string filePath = Directory.GetCurrentDirectory() + @"\audio\Processed\" + recordingFile;
        var memory = new MemoryStream();
        using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            await stream.CopyToAsync(memory);
        }
        memory.Position = 0;
        var types = GetMimeTypes();
        var ext = Path.GetExtension(filePath).ToLowerInvariant();
        return File(memory, types[ext], recordingFile);
    }

我正在为此使用 Blazor。事实证明,Blazor APIReponse 中间件中有一个 API 响应包装器。我不得不将我的 API 放入异常中,这样当我访问它时它就不会变成 JSON。终于成功了。

下面是 Blazor 中的API响应包装器。

var formattedRequest = await FormatRequest(request);
                    var originalBodyStream = httpContext.Response.Body;

                    using (var responseBody = new MemoryStream())
                    {
                        try
                        {
                            string responseBodyContent = null;

                            var response = httpContext.Response;

                            if (new string[] { "/api/localization", "/api/data", "/api/externalauth", "/api/download" }.Any(e => request.Path.StartsWithSegments(new PathString(e.ToLower()))))
                                await _next.Invoke(httpContext);
                            else
                            {
                                response.Body = responseBody;

                                await _next.Invoke(httpContext);

                                //wrap response in ApiResponse
                                if (httpContext.Response.StatusCode == Status200OK)
                                {
                                    responseBodyContent = await FormatResponse(response);
                                    await HandleSuccessRequestAsync(httpContext, responseBodyContent, Status200OK);
                                }
                                else
                                    await HandleNotSuccessRequestAsync(httpContext, httpContext.Response.StatusCode);
                            }