Created
December 25, 2021 09:58
-
-
Save hishamco/a95fe8944e3c894498bc9aae33c69366 to your computer and use it in GitHub Desktop.
CSV Content Result for ASP.NET Core
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.AspNetCore.Mvc; | |
public class CsvContentResult : ContentResult | |
{ | |
private const string _contentType = "text/csv"; | |
public CsvContentResult(string content) | |
{ | |
ContentType = _contentType; | |
Content = content; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@saineshwar this a simple implementation for retrieving CSV directly from within RazorPage / MVC action