1

I am working on a project with Web API on the server side and angularjs on the client side. One of the requirement is to retrieve data from database based on some parameters and export it in csv as well as pdf formats. We are using async/await pattern. I am kind of new to Web API and angularjs and did not find a good resource in this direction. Can anybody suggest anything that will help me getting started in the right direction ?

So far this is what I did but not succesful in getting the desired output.

// This is WEB API method
[HttpGet]
[Authorize]
[Route("ExportAppData")]
public IHttpActionResult ExportAppData()
{
    List<App> apps = _appRepository.GetAllApps();
    string csvData = ConvertToCSV(apps);
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    result.Content = new StringContent(csvData);
    result.Content.Headers.ContentType = new   MediaTypeHeaderValue("application/octet-stream");
    result.Content.Headers.ContentDisposition = new    ContentDispositionHeaderValue("attachment");
    result.Content.Headers.ContentDisposition.FileName = "file.csv";
    return Ok(result);
}

// This is angularjs function call to call the above method
function exportAppData() {
        return $http(
            {url: 'api/Apps/ExportAppData', 
            method: "GET",
            headers: {'Content-Type': 'application/octet-stream'}
            }
            );
    }

When I run I am getting an error message "The request contains an entity body but no Content-Type header. The inferred media type 'application/octet-stream' is not supported for this resource."

Any idea where I am missing something ?

1 Answer 1

1

You would need a custom MediaTypeFormatter

Read more at: ASP.NET Web API Series - Part 5: MediaTypeFormatter explained

Then you register it in WebApiConfig.cs

config.Formatters.Add(new PdfMediaTypeFormatter());

There's a Create PDF’s with ASP.NET Web Api post which you may find useful.

Personally i would just add razor views and return them as Web API introduced IHttpActionResult for returning HTTP messages that appeared to be a cross between HttpResponseMessage and the ActionResult mechanism from ASP.NET MVC.

Read more at:

Then maybe you can use Rotativa which uses wkhtmltopdf under the hood or iTextSharp.

wkhtmltopdf and wkhtmltoimage are open source (LGPLv3) command line tools to render HTML into PDF and various image formats using the QT Webkit rendering engine. These run entirely "headless" and do not require a display or display service.

Also you cannot use AJAX to download files you should use a simple HTML <form>.

There's also RazorEngine - a templating engine based on the Razor parser that you can use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.