BodyOrDefaultBinderMiddleware.cs 2.8 KB

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