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.
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.
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
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());
}
var teamIds = from rid in reviewerData
where rid.IsTeam.HasValue && rid.IsTeam.Value
select rid.ReviewerId;
if (teamIds.Any())
{
result.TeamReviewer = string.Join(",", teamIds);
}