Skip to content

Instantly share code, notes, and snippets.

@hishamco
Created December 25, 2021 09:58
Show Gist options
  • Save hishamco/a95fe8944e3c894498bc9aae33c69366 to your computer and use it in GitHub Desktop.
Save hishamco/a95fe8944e3c894498bc9aae33c69366 to your computer and use it in GitHub Desktop.
CSV Content Result for ASP.NET Core
using Microsoft.AspNetCore.Mvc;
public class CsvContentResult : ContentResult
{
private const string _contentType = "text/csv";
public CsvContentResult(string content)
{
ContentType = _contentType;
Content = content;
}
}
using System.Text;
namespace System.Collections.Generic
{
public static class EnumerableExtensions
{
public static string ToCsv(this IEnumerable source)
{
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
var result = new StringBuilder();
foreach (var item in source)
{
foreach (var property in item.GetType().GetProperties())
{
result.Append(property.GetValue(item).ToString()).Append(",");
}
result.Append(Environment.NewLine);
}
return result.ToString();
}
}
}
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
public class TestModel : PageModel
{
// Retreive CSV content from text
// public IActionResult OnGet() => new CsvContentResult("Hisham,https://www.github.com/hishamco");
// Retreive CSV content from entity
public IActionResult OnGet()
{
var users = _dbContext.Users.Select(u => new
{
Name = u.Name,
GitHubUrl = u.GitHubUrl
}).ToCsv();
return new CsvContentResult(users);
}
}
@hishamco
Copy link
Author

@saineshwar this a simple implementation for retrieving CSV directly from within RazorPage / MVC action

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment