Download file prompt when using WebAPI HttpRespons

2019-04-13 20:35发布

问题:

I have a method in my API that returns a 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);
        }
    }

In my MVC Web Apllication i have a controller Action that needs to call the API and return the file:

    [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;
    }

If i access the API url directly it prompts me for a username and password, and then the Save File dialogue appears, and i can download the file.

If i navigate to the Action in my Web Application then i get the following response output to screen:

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 

I take it i need to return a FileResult, but i have no clue as to how to convert the HttpResponseMessage to a FileResult.

回答1:

In your MVC controller you can try returning a FileResult, and use the File() method reading the response of your API as byte array.

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