ModelBindingContextExtension.cs 5.1 KB

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