Bhav
Bhav

Reputation: 2197

Forward file attachment from Web API to MVC controller

I've got a Web API that returns a csv file. If I make a GET request e.g. via. a browser, I get a popup to ask where to download the csv file:

HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);

result.Content = new StringContent(res);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = "export_" + DateTime.Now + ".csv"
};
return ResponseMessage(result);

I'm trying to call this API endpoint within another MVC controller and return the same csv file. How can I do this?

var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAPIEndpoint);
httpWebRequest.Method = "GET";

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

return httpResponse;

Upvotes: 0

Views: 131

Answers (1)

Sean
Sean

Reputation: 15144

Responses (routes) in MVC controllers are typically ActionResults. The httpResponse object you are returning, is an HttpWebResponse.

You should probably read the csv content (using GetResponseStream) from the httpResponse, and then return that csv content using an appropriate MVC ActionResult.

Upvotes: 1

Related Questions