43 lines
1.4 KiB
C#
43 lines
1.4 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// 忽略响应<see cref="IApiResult"/>.Data的自动camelCase
|
|
/// </summary>
|
|
[AttributeUsage(AttributeTargets.Method)]
|
|
public class ExcelResultAttribute : Attribute, IAsyncActionFilter
|
|
{
|
|
private readonly string _fileName;
|
|
|
|
public ExcelResultAttribute(string fileName)
|
|
{
|
|
_fileName = fileName;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
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<byte[]>)method.MakeGenericMethod(type).Invoke(null, new[] { v });
|
|
var data = await task;
|
|
|
|
r.Result = new FileContentResult(data, "application/vnd.ms-excel")
|
|
{
|
|
FileDownloadName = _fileName
|
|
};
|
|
}
|
|
} |