3

我的 API 中有一个返回 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 并返回文件的控制器操作:

    [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 

我认为我需要返回一个 FileResult,但我不知道如何将 HttpResponseMessage 转换为 FileResult。

4

1 回答 1

11

在您的 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");
}
于 2015-02-09T14:07:47.387 回答