UnifyResponseFilter.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System.Reflection;
  2. using Fw.Utility.UnifyResponse;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.AspNetCore.Mvc.Controllers;
  5. using Microsoft.AspNetCore.Mvc.Filters;
  6. namespace XF.Domain.Filters
  7. {
  8. public class UnifyResponseFilter : IActionFilter
  9. {
  10. /// <summary>
  11. /// Called before the action executes, after model binding is complete.
  12. /// </summary>
  13. /// <param name="context">The <see cref="T:Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext" />.</param>
  14. public void OnActionExecuting(ActionExecutingContext context)
  15. {
  16. }
  17. /// <summary>
  18. /// Called after the action executes, before the action result.
  19. /// </summary>
  20. /// <param name="context">The <see cref="T:Microsoft.AspNetCore.Mvc.Filters.ActionExecutedContext" />.</param>
  21. public void OnActionExecuted(ActionExecutedContext context)
  22. {
  23. if (context.Canceled || context.Exception != null)
  24. {
  25. return;
  26. }
  27. // if (context.ActionDescriptor is ControllerActionDescriptor action)
  28. // {
  29. // var origin = action?.MethodInfo.GetCustomAttribute(typeof(OriginResponseAttribute));
  30. // if (origin is not null) return;
  31. // }
  32. switch (context.Result)
  33. {
  34. case JsonResult jsonResult:
  35. if (jsonResult.Value is not null && jsonResult.Value is not ApiResponse)
  36. {
  37. jsonResult.Value = ApiResponse<object>.Success(jsonResult.Value);
  38. }
  39. return;
  40. case BadRequestResult _:
  41. case OkResult _:
  42. case FileResult _:
  43. context.HttpContext.Response.Headers.TryAdd("Access-Control-Expose-Headers", "Content-Disposition");
  44. break;
  45. case StatusCodeResult _:
  46. case BadRequestObjectResult _:
  47. // do nothing
  48. return;
  49. case ObjectResult objectResult:
  50. if (objectResult.Value is OpenResponse rsp)
  51. {
  52. context.Result = new OkObjectResult(rsp.Value);
  53. break;
  54. }
  55. if (objectResult.Value is ApiResponse) break;
  56. context.Result = new JsonResult(objectResult.Value == null
  57. ? new ApiResponse()
  58. : ApiResponse<object>.Success(objectResult.Value));
  59. break;
  60. case EmptyResult _:
  61. context.Result = new JsonResult(new ApiResponse());
  62. return;
  63. }
  64. }
  65. }
  66. }