自定义视图引擎VS自定义操作结果
-
27-09-2020 - |
题
我有一个方案,用户可以选择单击“下载”按钮,我应该创建一个CSV文件,其中包含历史记录数据,然后让用户在本地保存文件。正如我之前没有这样做的那样,我开始浏览如何做到这一点,并且基本上遇到了自定义视图引擎和自定义动作结果。
我的问题现在是这些的好处/缺点是什么?去的首选方法是什么?
csv文件,基本上仅包含带有几千行的标题和数据(最多约15列/字段)。所以真的没什么特别的。
解决方案
我可能会去进行自定义操作结果(我的示例中的实际序列化是用 filehelpers )完成:
public class CsvResult<T> : ActionResult
{
public IEnumerable<T> Records { get; private set; }
public CsvResult(IEnumerable<T> records)
{
Records = records;
}
public override void ExecuteResult(ControllerContext context)
{
var response = context.HttpContext.Response;
response.ContentType = "text/csv";
var engine = new FileHelperEngine(typeof(T));
engine.WriteStream(response.Output, Records);
}
}
[DelimitedRecord(",")]
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
public class HomeController : Controller
{
public ActionResult Index()
{
var customers = new[]
{
new Customer { Id = 1, Name = "customer 1" },
new Customer { Id = 2, Name = "customer 2" },
};
return new CsvResult<Customer>(customers);
}
}
.
您甚至可以通过使用扩展方法(在这种情况下在这种情况下泛滥和多余的泛型)来预更状态:
public static class ControllerExtensions
{
public static ActionResult Csv<T>(this Controller controller, IEnumerable<T> records)
{
return new CsvResult<T>(records);
}
}
.
然后简单:
public ActionResult Index()
{
var customers = new[]
{
new Customer { Id = 1, Name = "customer 1" },
new Customer { Id = 2, Name = "customer 2" },
};
return this.Csv(customers);
}
. 不隶属于 StackOverflow