1

Currently Using ASP.NET web API I'm able to return data in JSON format.

Now I'm trying to return data in csv (feed) format.

Is it possible to force web API to return data in CSV format.

Please Suggest something. Any kind of help is appreciated.

  • 1
    You need to implement a MediaTypeFormatter for csv. This link has an implementation for what you are looking for . http://www.tugberkugurlu.com/archive/creating-custom-csvmediatypeformatter-in-asp-net-web-api-for-comma-separated-values-csv-format – Rohith Jun 27 '17 at 06:06
  • https://stackoverflow.com/questions/29948809/web-api-return-csv-file – Marcus Höglund Jun 27 '17 at 06:14

3 Answers3

1

Create a class and derive from MediaTypeFormatter and add it to the Formatters on the HttpConfiguration:

https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/media-formatters

1

It is indeed possible to return data in CSV format, but you will need to hand-craft a small amount of code to do it. My suggestion is to write a helper method on your class to do so. For example -

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set;  }
    public string Address { get; set; }


    public string PersonToCSVLine
    {
        get
        {
            //Places commas between fields, string quotes around address
            return String.Concat(this.Id.ToString(), "," , this.FirstName, "," , this.LastName, ",\"", this.Address, "\"" );
        }
    }
}

To output CSV to web page - assuming you have a collection of objects with a helper method similar to above - you could use this method to generate the output. A sample MVC controller method is shown below

public ActionResult DisplayCSV()
    {

        List<person> People = populatePeople();
        StringBuilder sb = new StringBuilder();

        foreach(var person in People)
        {
            sb.AppendLine(person.PersonToCSVLine);

        }
        return Content(sb.ToString());

    }
Tom Wass
  • 149
  • 1
  • 5
0
 var teamIds = from rid in reviewerData
                          where rid.IsTeam.HasValue && rid.IsTeam.Value
                          select rid.ReviewerId;

            if (teamIds.Any())
            {
                result.TeamReviewer = string.Join(",", teamIds);
            }