在ASP.NET Core中,如果你想返回一个CSV文件作为ActionResult,你可以使用以下代码来解决编码问题:
public class CsvActionResult : IActionResult
{
private readonly string _csvString;
private readonly string _fileName;
public CsvActionResult(string csvString, string fileName)
{
_csvString = csvString;
_fileName = fileName;
}
public Task ExecuteResultAsync(ActionContext context)
{
var response = context.HttpContext.Response;
response.ContentType = "text/csv";
response.Headers.Add("Content-Disposition", $"attachment; filename={_fileName}");
// Convert the CSV string to bytes with the correct encoding
var csvBytes = Encoding.UTF8.GetBytes(_csvString);
return response.Body.WriteAsync(csvBytes, 0, csvBytes.Length);
}
}
public IActionResult ExportCsv()
{
// Generate your CSV string here
var csvString = "Name,Age\nJohn,30\nJane,25";
// Create a new CsvActionResult with the CSV string and file name
var csvResult = new CsvActionResult(csvString, "data.csv");
return csvResult;
}
通过这种方式,你可以返回一个CSV文件作为ActionResult,并且确保CSV文件的编码正确。在上面的示例中,我们使用了UTF-8编码,你也可以根据需要使用其他编码。