BodyOrDefaultBinderMiddleware.cs 2.1 KB

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