using Dlhis.ExcelHelper;
using Kurisu.AspNetCore.DataAccess.Dto;
using Kurisu.AspNetCore.UnifyResultAndValidation.Abstractions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace Dlhis.Canteen;
///
/// 忽略响应.Data的自动camelCase
///
[AttributeUsage(AttributeTargets.Method)]
public class ExcelResultAttribute : Attribute, IAsyncActionFilter
{
private readonly string _fileName;
public ExcelResultAttribute(string fileName)
{
_fileName = fileName;
}
///
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var r = await next();
var or = r.Result as ObjectResult;
var v = or.Value;
var type = or.DeclaredType.GenericTypeArguments[0];
if (or.DeclaredType.IsGenericType && or.DeclaredType.GetGenericTypeDefinition() == typeof(Pagination<>))
{
v = v.GetType().GetProperty("Data").GetValue(v, null);
}
var method = typeof(ExcelExtensions).GetMethod(nameof(ExcelExtensions.ToExcelBytesAsync));
var task = (Task)method.MakeGenericMethod(type).Invoke(null, new[] { v });
var data = await task;
r.Result = new FileContentResult(data, "application/vnd.ms-excel")
{
FileDownloadName = _fileName
};
}
}