我是这样做的:
将新的 DownloadController.cs 添加到名为 Controllers 的文件夹中
[Controller, Microsoft.AspNetCore.Mvc.Route("/[controller]/[action]")]
public class DownloadController : Controller
{
private readonly IDataCombinerService DataCombinerService;
private readonly IDataLocatorService DataLocatorService;
public DownloadController(IDataCombinerService dataCombinerService, IDataLocatorService dataLocatorService)
{
DataCombinerService = dataCombinerService;
DataLocatorService = dataLocatorService;
}
[HttpGet]
[ActionName("Accounts")]
public async Task<IActionResult> Accounts()
{
var cts = new CancellationTokenSource();
var Accounts = await DataCombinerService.CombineAccounts(await DataLocatorService.GetDataLocationsAsync(cts.Token), cts.Token);
var json = JsonSerializer.SerializeToUtf8Bytes(Accounts, Accounts.GetType(), new JsonSerializerOptions(JsonSerializerDefaults.Web) { WriteIndented = true });
var stream = new MemoryStream(json);
var fResult = new FileStreamResult(stream, MediaTypeNames.Application.Json)
{
FileDownloadName = $"Account Export {DateTime.Now.ToString("yyyyMMdd")}.json"
};
return fResult;
}
[HttpGet]
public IActionResult Index()
{
return View();
}
}
严格来说,这里不需要异步,因为它不需要处理任何其他内容,但该方法用于在屏幕上显示相同的结果。
然后在 Startup.cs
app.UseEndpoints(endpoints =>
添加:
endpoints.MapControllerRoute(
name: "default",
defaults: new { action = "Index" },
pattern: "{controller}/{action}");
endpoints.MapControllers();
同样,严格来说,默认值不是必需的,它是标准的 MVC 控制器。
然后,这就像经典的 MVC 响应一样起作用,因此您可以从您喜欢的任何来源发回任何文件。使用中间件服务在视图和下载器控制器之间保存临时数据可能会有所帮助,以便客户端下载相同的数据。