BodyOrDefaultBinderMiddleware.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System.Net.Mime;
  2. using System.Text;
  3. using System.Xml.Linq;
  4. using Microsoft.AspNetCore.Http;
  5. using Microsoft.Extensions.Logging;
  6. using Newtonsoft.Json.Linq;
  7. namespace Masuit.Tools.AspNetCore.ModelBinder;
  8. public sealed class BodyOrDefaultBinderMiddleware(RequestDelegate next, ILogger<BodyOrDefaultBinderMiddleware> logger)
  9. {
  10. public Task Invoke(HttpContext context)
  11. {
  12. var contentType = context.Request.ContentType;
  13. string mediaType;
  14. var charSet = "utf-8";
  15. if (string.IsNullOrWhiteSpace(contentType))
  16. {
  17. //表单提交
  18. mediaType = "application/x-www-form-urlencoded";
  19. }
  20. else
  21. {
  22. try
  23. {
  24. var type = new ContentType(contentType);
  25. if (!string.IsNullOrWhiteSpace(type.CharSet))
  26. {
  27. charSet = type.CharSet;
  28. }
  29. mediaType = type.MediaType.ToLower();
  30. }
  31. catch (Exception e)
  32. {
  33. logger.LogError(e, "Parsing contentType failed:" + contentType);
  34. mediaType = "multipart/form-data";
  35. }
  36. }
  37. var encoding = Encoding.GetEncoding(charSet);
  38. if (mediaType == "application/x-www-form-urlencoded")
  39. {
  40. //普通表单提交
  41. }
  42. else if (mediaType == "multipart/form-data")
  43. {
  44. //带有文件的表单提交
  45. }
  46. else if (mediaType == "application/json")
  47. {
  48. var body = context.GetBodyString(encoding)?.Trim();
  49. if (string.IsNullOrWhiteSpace(body))
  50. {
  51. return next(context);
  52. }
  53. if (!(body.StartsWith("{") && body.EndsWith("}")))
  54. {
  55. return next(context);
  56. }
  57. try
  58. {
  59. context.Items.AddOrUpdate("BodyOrDefaultModelBinder@JsonBody", _ => JObject.Parse(body), (_, _) => JObject.Parse(body));
  60. return next(context);
  61. }
  62. catch (Exception ex)
  63. {
  64. logger.LogError(ex, "Parsing json failed:" + body);
  65. return next(context);
  66. }
  67. }
  68. else if (mediaType == "application/xml")
  69. {
  70. var body = context.GetBodyString(encoding)?.Trim();
  71. if (string.IsNullOrWhiteSpace(body))
  72. {
  73. return next(context);
  74. }
  75. try
  76. {
  77. context.Items.AddOrUpdate("BodyOrDefaultModelBinder@XmlBody", _ => XDocument.Parse(body), (_, _) => XDocument.Parse(body));
  78. return next(context);
  79. }
  80. catch (Exception ex)
  81. {
  82. logger.LogError(ex, "Parsing xml failed:" + body);
  83. return next(context);
  84. }
  85. }
  86. return next(context);
  87. }
  88. }