CRUD Operations In ASP.NET Core 1.0 MVC Application - Part Eight

Let's discuss how to export data or lists in CSV format. For this purpose, we will implement Custom Response Formatter CsvOutputFormatter and a generic helper CsvWriter to convert any List of objects to CSV format. We are going to extend our application from our last discussion CRUD Operations In ASP.NET Core 1.0 MVC Application - Part Seven.

Add CsvWriter in WebApplicationCore.NetCore

Open existing Solution in Visual Studio 2015.

Now, add a new folder "Common" in WebApplicationCore.NetCore.

Open Context Menu of project >> Add >> New Folder.

Name it Common.

Now, add a new class CsvWriter.cs in Common folder in WebApplicationCore.NetCore.

Add required implementation in CsvWriter to generate CSV string for provided list of objects. CsvWriter is a helper class and it provides facility to generate CSV of provided List of objects. We have changed it for our requirements, please refer to How To Implement .NET Core CSV Writer for more details.

Implement Custom Output Formatter in CsvOutputFormatter class to generate response in CSV format using CsvWriter. To create a new Custom Output Formatter we can use one of following approaches

Inherent existing output formatter base class TextOutputFormatter, OutputFormatter or StreamOutputFormatter as per requirement. For example, JsonOutputFormatter and XmlSerializerOutputFormatter inherit TextOutputFormatter. Although, this approach provides many features out of box due to base class, yet it makes formatter little heavier.

Alternatively, Implement IOutputFormatter interface and we just have to implement two methods: CanWriteResult and WriteAsync. Where CanWriteResult is used to check if this formatter can be used to process response or not, while WriteAsync method performs actual processing on response. We have used this approach as it is simple and efficient.

ASP.NET Core provisions us to implement Custom Response Formatter and Custom Request Formatter separately. In this way, we can use any kind of Response and Request formatter as per requirements. We will discuss Custom Response and Request Formatter in detail in future sessions.

We also need to register CsvOutputFormatter, for this purpose, we register it in ConfigureServices method of Startup class with MVC service as Setup Action. Simply put, we have to add CsvOutputFormatter in collection of OutputFormatters of MVC Service.

Now, add a new action method GetCsv in WebApplicationCore.NetCore.ContactController class. It is similar to Index Action Method with the exception that it returns List<ContactListVM> and has [Produces("text/csv")] attribute to mark content type to enforce ustilizationof CsvOutputFormatter. We are explicitly checking content type == "text/csv" in CanWriteResult.