ModelBindingContextExtension.cs 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. using System.Net.Mime;
  2. using System.Text;
  3. using Microsoft.AspNetCore.Mvc.Controllers;
  4. using Microsoft.AspNetCore.Mvc.ModelBinding;
  5. using Microsoft.Extensions.Primitives;
  6. using Newtonsoft.Json;
  7. using Newtonsoft.Json.Linq;
  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="bindingContext"></param>
  75. public static bool TrySetDefaultValue(this ModelBindingContext bindingContext)
  76. {
  77. var attr = bindingContext.GetAttribute<FromBodyOrDefaultAttribute>();
  78. if (attr.DefaultValue != null)
  79. {
  80. var targetValue = attr.DefaultValue.ChangeType(bindingContext.ModelType);
  81. bindingContext.Result = ModelBindingResult.Success(targetValue);
  82. return true;
  83. }
  84. return false;
  85. }
  86. /// <summary>
  87. /// 转换为对应类型
  88. /// </summary>
  89. /// <param name="this"></param>
  90. public static T ConvertObjectTo<T>(this object @this)
  91. {
  92. return (T)ConvertObject(@this, typeof(T));
  93. }
  94. /// <summary>
  95. /// 转换为对应类型
  96. /// </summary>
  97. /// <param name="this"></param>
  98. /// <param name="type"></param>
  99. public static object ConvertObject(this object @this, Type type)
  100. {
  101. object value;
  102. if (@this is string str)
  103. {
  104. str = str.Trim();
  105. if ((str.StartsWith("[") && str.EndsWith("]")) || str.StartsWith("{") && str.EndsWith("}"))
  106. {
  107. value = JsonConvert.DeserializeObject(str, type);
  108. }
  109. else if ((str.StartsWith("\"[") && str.EndsWith("]\"")) || str.StartsWith("\"{") && str.EndsWith("}\""))
  110. {
  111. // json字符串 又被 json序列化 的情况
  112. var objects = JsonConvert.DeserializeObject(str);
  113. value = JsonConvert.SerializeObject(objects).ConvertObject(type);
  114. }
  115. else
  116. {
  117. var text = JsonConvert.SerializeObject(@this);
  118. value = JsonConvert.DeserializeObject(text, type);
  119. }
  120. }
  121. else if (@this is StringValues values)
  122. {
  123. var text = values.ToString();
  124. if (type.IsSimpleArrayType() || type.IsSimpleListType())
  125. {
  126. text = JsonConvert.SerializeObject(values);
  127. value = JsonConvert.DeserializeObject(text, type);
  128. }
  129. else
  130. {
  131. text = JsonConvert.SerializeObject(text);
  132. value = JsonConvert.DeserializeObject(text, type);
  133. }
  134. }
  135. else if (@this is JToken)
  136. {
  137. var text = JsonConvert.SerializeObject(@this);
  138. value = JsonConvert.DeserializeObject(text, type);
  139. }
  140. else
  141. {
  142. var text = JsonConvert.SerializeObject(@this);
  143. value = JsonConvert.DeserializeObject(text, type);
  144. }
  145. return value;
  146. }
  147. }