BodyOrDefaultBinderMiddleware.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. var type = new ContentType(contentType);
  23. if (!string.IsNullOrWhiteSpace(type.CharSet))
  24. {
  25. charSet = type.CharSet;
  26. }
  27. mediaType = type.MediaType.ToLower();
  28. }
  29. var encoding = Encoding.GetEncoding(charSet);
  30. if (mediaType == "application/x-www-form-urlencoded")
  31. {
  32. //普通表单提交
  33. }
  34. else if (mediaType == "multipart/form-data")
  35. {
  36. //带有文件的表单提交
  37. }
  38. else if (mediaType == "application/json")
  39. {
  40. var body = context.GetBodyString(encoding)?.Trim();
  41. if (string.IsNullOrWhiteSpace(body))
  42. {
  43. return next(context);
  44. }
  45. if (!(body.StartsWith("{") && body.EndsWith("}")))
  46. {
  47. return next(context);
  48. }
  49. try
  50. {
  51. context.Items.AddOrUpdate("BodyOrDefaultModelBinder@JsonBody", _ => JObject.Parse(body), (_, _) => JObject.Parse(body));
  52. return next(context);
  53. }
  54. catch (Exception ex)
  55. {
  56. logger.LogError(ex, "Parsing json failed:" + body);
  57. return next(context);
  58. }
  59. }
  60. else if (mediaType == "application/xml")
  61. {
  62. var body = context.GetBodyString(encoding)?.Trim();
  63. if (string.IsNullOrWhiteSpace(body))
  64. {
  65. return next(context);
  66. }
  67. try
  68. {
  69. context.Items.AddOrUpdate("BodyOrDefaultModelBinder@XmlBody", _ => XDocument.Parse(body), (_, _) => XDocument.Parse(body));
  70. return next(context);
  71. }
  72. catch (Exception ex)
  73. {
  74. logger.LogError(ex, "Parsing xml failed:" + body);
  75. return next(context);
  76. }
  77. }
  78. return next(context);
  79. }
  80. }