使用WebAPI HttpResponseMessage时下载文件提示

时间:2015-02-09 13:09:10

标签: c# asp.net-mvc asp.net-web-api httpresponse fileresult

我的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 Apllication中,我有一个需要调用API并返回文件的控制器Action:

    [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网址,它会提示我输入用户名和密码,然后会出现“保存文件”对话框,我可以下载该文件。

如果我导航到我的Web应用程序中的Action,那么我得到以下响应输出到屏幕:

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。

1 个答案:

答案 0 :(得分:8)

在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");
}