FromBodyOrDefaultModelBinder.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. using System.Collections;
  2. using System.Net.Mime;
  3. using System.Reflection;
  4. using System.Xml.Linq;
  5. using Masuit.Tools.Systems;
  6. using Microsoft.AspNetCore.Mvc.ModelBinding;
  7. using Microsoft.Extensions.DependencyInjection;
  8. using Microsoft.Extensions.Logging;
  9. using Microsoft.Extensions.Primitives;
  10. using Newtonsoft.Json.Linq;
  11. namespace Masuit.Tools.AspNetCore.ModelBinder;
  12. public class FromBodyOrDefaultModelBinder(ILogger<FromBodyOrDefaultModelBinder> logger) : IModelBinder
  13. {
  14. private static readonly List<BindType> BindTypes =
  15. [
  16. BindType.Query,
  17. BindType.Body,
  18. BindType.Header,
  19. BindType.Form,
  20. BindType.Cookie,
  21. BindType.Route
  22. ];
  23. public Task BindModelAsync(ModelBindingContext bindingContext)
  24. {
  25. var context = bindingContext.HttpContext;
  26. var attr = bindingContext.GetAttribute<FromBodyOrDefaultAttribute>();
  27. var field = attr?.FieldName ?? bindingContext.FieldName;
  28. var modelType = bindingContext.ModelType;
  29. object value = null;
  30. if (attr != null)
  31. {
  32. if (modelType.IsSimpleType() || modelType.IsSimpleArrayType() || modelType.IsSimpleListType())
  33. {
  34. if (attr.Type == BindType.Default)
  35. {
  36. foreach (var type in BindTypes)
  37. {
  38. value = GetBindingValue(bindingContext, type, field, modelType);
  39. if (value != null)
  40. {
  41. break;
  42. }
  43. }
  44. }
  45. else
  46. {
  47. foreach (var type in attr.Type.Split())
  48. {
  49. value = GetBindingValue(bindingContext, type, field, modelType);
  50. if (value != null)
  51. {
  52. break;
  53. }
  54. }
  55. }
  56. }
  57. else
  58. {
  59. if (bindingContext.HttpContext.Items.TryGetValue("BodyOrDefaultModelBinder@JsonBody", out var obj) && obj is JObject json)
  60. {
  61. if (modelType.IsArray || modelType.IsGenericType && modelType.GenericTypeArguments.Length == 1)
  62. {
  63. if (json.TryGetValue(field, StringComparison.OrdinalIgnoreCase, out var jtoken))
  64. {
  65. value = jtoken.ToObject(modelType);
  66. }
  67. else
  68. {
  69. logger.LogWarning($"TraceIdentifier:{context.TraceIdentifier},BodyOrDefaultModelBinder从{json}中获取{field}失败!");
  70. }
  71. }
  72. else
  73. {
  74. // 可能是 字典或者实体 类型,尝试将modeltype 当初整个请求参数对象
  75. try
  76. {
  77. value = json.ToObject(modelType);
  78. }
  79. catch (Exception e)
  80. {
  81. logger.LogError(e, e.Message, json.ToString());
  82. }
  83. }
  84. }
  85. if (value == null)
  86. {
  87. var (requestData, keys) = GetRequestData(bindingContext, modelType);
  88. if (keys.Any())
  89. {
  90. var instance = Activator.CreateInstance(modelType);
  91. switch (requestData)
  92. {
  93. case IEnumerable<KeyValuePair<string, StringValues>> stringValues:
  94. {
  95. foreach (var item in stringValues)
  96. {
  97. var property = modelType.GetProperty(item.Key, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
  98. if (property != null)
  99. {
  100. property.SetValue(instance, item.Value.ConvertObject(property.PropertyType));
  101. }
  102. }
  103. break;
  104. }
  105. case IEnumerable<KeyValuePair<string, string>> strs:
  106. {
  107. //处理Cookie
  108. foreach (var item in strs)
  109. {
  110. var property = modelType.GetProperty(item.Key, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
  111. if (property != null)
  112. {
  113. property.SetValue(instance, item.Value.ConvertObject(property.PropertyType));
  114. }
  115. }
  116. break;
  117. }
  118. case IEnumerable<KeyValuePair<string, object>> objects:
  119. {
  120. //处理路由
  121. foreach (var item in objects)
  122. {
  123. var property = modelType.GetProperty(item.Key, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
  124. if (property != null)
  125. {
  126. property.SetValue(instance, item.Value.ConvertObject(property.PropertyType));
  127. }
  128. }
  129. break;
  130. }
  131. }
  132. value = instance;
  133. }
  134. }
  135. }
  136. if (value == null && attr.DefaultValue != null)
  137. {
  138. value = attr.DefaultValue.ChangeType(modelType);
  139. }
  140. }
  141. if (value != null)
  142. {
  143. bindingContext.Result = ModelBindingResult.Success(value);
  144. }
  145. return Task.CompletedTask;
  146. }
  147. private static (IEnumerable data, List<string> keys) GetRequestData(ModelBindingContext bindingContext, Type type)
  148. {
  149. var request = bindingContext.HttpContext.Request;
  150. var props = type.GetProperties().Select(t => t.Name).ToList();
  151. var query = props.Except(request.Query.Keys, StringComparer.OrdinalIgnoreCase).ToList();
  152. var headers = props.Except(request.Headers.Keys, StringComparer.OrdinalIgnoreCase).ToList();
  153. var cookies = props.Except(request.Cookies.Keys, StringComparer.OrdinalIgnoreCase).ToList();
  154. var routes = props.Except(bindingContext.ActionContext.RouteData.Values.Keys, StringComparer.OrdinalIgnoreCase).ToList();
  155. var list = new List<KeyValuePair<List<string>, IEnumerable>>()
  156. {
  157. new(query, request.Query),
  158. new(headers, request.Headers),
  159. new(cookies, request.Cookies),
  160. new(routes, bindingContext.ActionContext.RouteData.Values),
  161. };
  162. if (request.HasFormContentType && request.Form.Count > 0)
  163. {
  164. var forms = props.Except(request.Form.Keys, StringComparer.OrdinalIgnoreCase).ToList();
  165. list.Add(new KeyValuePair<List<string>, IEnumerable>(forms, request.Form));
  166. }
  167. var kv = list.OrderBy(t => t.Key.Count).FirstOrDefault();
  168. return (kv.Value, props.Except(kv.Key).ToList());
  169. }
  170. /// <summary>
  171. /// 获取要绑定的值
  172. /// </summary>
  173. /// <param name="bindingContext"></param>
  174. /// <param name="bindType"></param>
  175. /// <param name="fieldName"></param>
  176. /// <param name="modelType"></param>
  177. private object GetBindingValue(ModelBindingContext bindingContext, BindType bindType, string fieldName, Type modelType)
  178. {
  179. var context = bindingContext.HttpContext;
  180. var mediaType = string.Empty;
  181. if (!string.IsNullOrWhiteSpace(context.Request.ContentType))
  182. {
  183. try
  184. {
  185. var contentType = new ContentType(context.Request.ContentType);
  186. mediaType = contentType.MediaType.ToLower();
  187. }
  188. catch (Exception ex)
  189. {
  190. logger.LogError(ex, ex.Message, context.Request.ContentType);
  191. }
  192. }
  193. object targetValue = null;
  194. switch (bindType)
  195. {
  196. case BindType.Body:
  197. switch (mediaType)
  198. {
  199. case "application/json":
  200. {
  201. if (bindingContext.HttpContext.Items.TryGetValue("BodyOrDefaultModelBinder@JsonBody", out var obj) && obj is JObject json && json.TryGetValue(fieldName, StringComparison.OrdinalIgnoreCase, out var values))
  202. {
  203. targetValue = values.ConvertObject(modelType);
  204. }
  205. }
  206. break;
  207. case "application/xml":
  208. {
  209. if (bindingContext.HttpContext.Items.TryGetValue("BodyOrDefaultModelBinder@XmlBody", out var obj) && obj is XDocument xml)
  210. {
  211. var xmlElt = xml.Element(fieldName);
  212. if (xmlElt != null)
  213. {
  214. targetValue = xmlElt.Value.ConvertObject(modelType);
  215. }
  216. }
  217. break;
  218. }
  219. }
  220. break;
  221. case BindType.Query:
  222. {
  223. if (context.Request.Query is { Count: > 0 } && context.Request.Query.TryGetValue(fieldName, out var values))
  224. {
  225. targetValue = values.ConvertObject(modelType);
  226. }
  227. }
  228. break;
  229. case BindType.Form:
  230. {
  231. if (context.Request is { HasFormContentType: true, Form.Count: > 0 } && context.Request.Form.TryGetValue(fieldName, out var values))
  232. {
  233. targetValue = values.ConvertObject(modelType);
  234. }
  235. }
  236. break;
  237. case BindType.Header:
  238. {
  239. if (context.Request.Headers is { Count: > 0 } && context.Request.Headers.TryGetValue(fieldName, out var values))
  240. {
  241. targetValue = values.ConvertObject(modelType);
  242. }
  243. }
  244. break;
  245. case BindType.Cookie:
  246. {
  247. if (context.Request.Cookies is { Count: > 0 } && context.Request.Cookies.TryGetValue(fieldName, out var values))
  248. {
  249. targetValue = values.ConvertObject(modelType);
  250. }
  251. }
  252. break;
  253. case BindType.Route:
  254. {
  255. if (bindingContext.ActionContext.RouteData.Values is { Count: > 0 } && bindingContext.ActionContext.RouteData.Values.TryGetValue(fieldName, out var values))
  256. {
  257. targetValue = values.ConvertObject(modelType);
  258. }
  259. }
  260. break;
  261. case BindType.Services:
  262. targetValue = bindingContext.ActionContext.HttpContext.RequestServices.GetRequiredService(modelType);
  263. break;
  264. }
  265. return targetValue;
  266. }
  267. }