1

In my application I have a few grids that each get their data source from an ApiController action. I want to add an option for the user to export these grid into either CSV, PDF, Excel, etc. Writing code to convert the datasource to the expected format is not problem. The problem is that I want to write re-usable code. Currently I have a separate action for each grid.

I could very easily add a new Export controller with matching actions that call into the same logic as the ApiController, but that means if I have five ApiController actions I will need five additional Controller actions.

What i'm wondering if if there was a way I could make a single export Controller action, but somehow pass the details for the ApiController to it.

Any suggestions?

Kyle
  • 17,317
  • 32
  • 140
  • 246
  • I think you should specify Accept header in requests. Basing on specified content type in the header an appropriate converter on the server will be used. – Shrike Jan 24 '13 at 17:14
  • Possible duplicate of [How to return a file (FileContentResult) in ASP.NET WebAPI](http://stackoverflow.com/questions/26038856/how-to-return-a-file-filecontentresult-in-asp-net-webapi) – NoWar Aug 04 '16 at 19:28
  • @Dimi I think you should flag the other question as the duplicate. This question was asked more than a year before. – Kyle Aug 05 '16 at 08:21

1 Answers1

0

Here is what I found:

Instead of returning StreamContent as the Content, I can make it work with ByteArrayContent.

[HttpGet]
public HttpResponseMessage Generate()
{
    var stream = new MemoryStream();
    // processing the stream.

    var result = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new ByteArrayContent(stream.GetBuffer())
    };
    result.Content.Headers.ContentDisposition =
        new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
    {
        FileName = "CertificationCard.pdf"
    };
    result.Content.Headers.ContentType =
        new MediaTypeHeaderValue("application/octet-stream");

    return result;
}
NoWar
  • 36,338
  • 80
  • 323
  • 498