ModelBindingContextExtension.cs 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. using System.Net.Mime;
  2. using System.Text;
  3. using Microsoft.AspNetCore.Http;
  4. using Microsoft.AspNetCore.Mvc.Controllers;
  5. using Microsoft.AspNetCore.Mvc.ModelBinding;
  6. using Microsoft.Extensions.Primitives;
  7. using Newtonsoft.Json;
  8. namespace Masuit.Tools.AspNetCore.ModelBinder;
  9. internal static class ModelBindingContextExtension
  10. {
  11. /// <summary>
  12. /// 获取绑定参数对应的 Attribute
  13. /// </summary>
  14. /// <typeparam name="T">Attribute对象</typeparam>
  15. /// <param name="bindingContext">绑定参数上下文</param>
  16. /// <param name="parameterName">参数名称</param>
  17. /// <returns></returns>
  18. public static T GetAttribute<T>(this ModelBindingContext bindingContext, string parameterName = null) where T : Attribute
  19. {
  20. var fieldName = parameterName ?? bindingContext.FieldName;
  21. var ctrlActionDesc = bindingContext.ActionContext.ActionDescriptor as ControllerActionDescriptor;
  22. var fieldParameter = ctrlActionDesc!.MethodInfo.GetParameters().Single(p => p.Name == fieldName);
  23. return fieldParameter.GetCustomAttributes(typeof(T), false).Single() as T;
  24. }
  25. /// <summary>
  26. /// 判断该次请求体Body是否是Json内容类型
  27. /// </summary>
  28. /// <param name="httpContext"></param>
  29. /// <param name="charSet"></param>
  30. /// <returns></returns>
  31. public static bool IsJsonContent(this HttpContext httpContext, out string charSet)
  32. {
  33. string strContentType = httpContext.Request.ContentType;
  34. if (string.IsNullOrEmpty(strContentType))
  35. {
  36. charSet = null;
  37. return false;
  38. }
  39. var contentType = new ContentType(strContentType);
  40. charSet = contentType.CharSet;
  41. return contentType.MediaType.ToLower() == "application/json";
  42. }
  43. /// <summary>
  44. /// 获取请求体Body字符串内容
  45. /// </summary>
  46. /// <param name="context"></param>
  47. /// <param name="encoding"></param>
  48. /// <returns></returns>
  49. public static string GetBodyString(this HttpContext context, Encoding encoding)
  50. {
  51. context.Request.EnableBuffering(); //Ensure the HttpRequest.Body can be read multipletimes
  52. int contentLen = 255;
  53. if (context.Request.ContentLength != null)
  54. {
  55. contentLen = (int)context.Request.ContentLength;
  56. }
  57. var body = context.Request.Body;
  58. string bodyText;
  59. if (contentLen <= 0)
  60. {
  61. bodyText = "";
  62. }
  63. else
  64. {
  65. using var reader = new StreamReader(body, encoding, true, contentLen, true);
  66. bodyText = reader.ReadToEndAsync().Result;
  67. }
  68. body.Position = 0;
  69. return bodyText;
  70. }
  71. /// <summary>
  72. /// 转换为对应类型
  73. /// </summary>
  74. /// <param name="this"></param>
  75. /// <param name="type"></param>
  76. public static object ConvertObject(this object @this, Type type)
  77. {
  78. object value;
  79. if (@this is string str)
  80. {
  81. str = str.Trim();
  82. if ((str.StartsWith('[') && str.EndsWith(']')) || str.StartsWith('{') && str.EndsWith('}'))
  83. {
  84. value = JsonConvert.DeserializeObject(str, type);
  85. }
  86. else if ((str.StartsWith("\"[") && str.EndsWith("]\"")) || str.StartsWith("\"{") && str.EndsWith("}\""))
  87. {
  88. // json字符串 又被 json序列化 的情况
  89. var objects = JsonConvert.DeserializeObject(str);
  90. value = JsonConvert.SerializeObject(objects).ConvertObject(type);
  91. }
  92. else
  93. {
  94. var text = JsonConvert.SerializeObject(@this);
  95. value = JsonConvert.DeserializeObject(text, type);
  96. }
  97. }
  98. else if (@this is StringValues values)
  99. {
  100. var text = values.ToString();
  101. if (type.IsSimpleArrayType() || type.IsSimpleListType())
  102. {
  103. text = JsonConvert.SerializeObject(values);
  104. value = JsonConvert.DeserializeObject(text, type);
  105. }
  106. else
  107. {
  108. text = JsonConvert.SerializeObject(text);
  109. value = JsonConvert.DeserializeObject(text, type);
  110. }
  111. }
  112. else
  113. {
  114. var text = JsonConvert.SerializeObject(@this);
  115. value = JsonConvert.DeserializeObject(text, type);
  116. }
  117. return value;
  118. }
  119. }