使用WebAPI HttpResponseMessage时下载文件提示

Download file prompt when using WebAPI HttpResponseMessage

我的 API 中有一个方法 return 是一个 HttpResponseMessage:

    [HttpGet, HoodPeekAuthFilter]
    public HttpResponseMessage GlobalOverview()
    {
        try
        {
            StatsRepo _statsRepo = new StatsRepo();

            string file = _statsRepo.IncidentData().AsCSVString();

            if (file == null)
            {
                return Request.CreateResponse(HttpStatusCode.NoContent);
            }

            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
            result.Content = new StringContent(file);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            result.Content.Headers.ContentDisposition.FileName = "GlobalOverview.csv";

            return result;
        }
        catch (Exception ex)
        {
            return Request.CreateResponse(HttpStatusCode.InternalServerError);
        }
    }

在我的 MVC Web 应用程序中,我有一个需要调用 API 和 return 文件的控制器操作:

    [Authorize]
    [HttpGet]
    public HttpResponseMessage GlobalOverview()
    {
        HttpResponseMessage file = new HttpResponseMessage();
        using (HttpClient httpClient = new HttpClient())
        {
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(this.UserName + ':' + this.Password)));
            Task<HttpResponseMessage> response = httpClient.GetAsync("api.someDomain/Reporting/GlobalOverview");
            file = response.Result;
        }

        return file;
    }

如果我直接访问 API url,它会提示我输入用户名和密码,然后出现“保存文件”对话框,我可以下载文件。

如果我导航到我的 Web 应用程序中的操作,那么我会在屏幕上收到以下响应输出:

StatusCode: 200, 
ReasonPhrase: 'OK', 
Version: 1.1, 
Content: System.Net.Http.StreamContent, 
Headers: { Pragma: no-cache X-SourceFiles: = XXXXXXX
Content-Disposition: attachment; 
filename=GlobalOverview.csv 
Content-Type: application/octet-stream Expires: -1 

我认为我需要 return FileResult,但我不知道如何将 HttpResponseMessage 转换为 FileResult。

在您的 MVC 控制器中,您可以尝试返回一个 FileResult,并使用 File() 方法读取您的 API 作为字节数组的响应。

[Authorize]
[HttpGet]
public FileResult GlobalOverview()
{
    HttpResponseMessage file = new HttpResponseMessage();
    using (HttpClient httpClient = new HttpClient())
    {
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(this.UserName + ':' + this.Password)));
        Task<HttpResponseMessage> response = httpClient.GetAsync("api.someDomain/Reporting/GlobalOverview");
        file = response.Result;
    }

    return File(file.Content.ReadAsByteArrayAsync().Result, "application/octet-stream", "GlobalOverview.csv");
}