FromBodyOrDefaultModelBinder.cs 12 KB

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