FromBodyOrDefaultModelBinder.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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. if (json.TryGetValue(field, StringComparison.OrdinalIgnoreCase, out var jtoken))
  86. {
  87. if (jtoken.Type is JTokenType.String)
  88. {
  89. jtoken.Value<string>().TryConvertTo(modelType, out value);
  90. }
  91. else
  92. {
  93. value = jtoken.ToObject(modelType);
  94. }
  95. }
  96. else
  97. {
  98. value = json.ToObject(modelType);
  99. }
  100. }
  101. catch (Exception e)
  102. {
  103. logger.LogError(e, e.Message, json.ToString());
  104. exception = e;
  105. }
  106. }
  107. }
  108. if (value == null)
  109. {
  110. var (requestData, keys) = GetRequestData(bindingContext, modelType);
  111. if (keys.Any())
  112. {
  113. var instance = Activator.CreateInstance(modelType);
  114. switch (requestData)
  115. {
  116. case IEnumerable<KeyValuePair<string, StringValues>> stringValues:
  117. {
  118. foreach (var item in stringValues)
  119. {
  120. var property = modelType.GetProperty(item.Key, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
  121. if (property != null)
  122. {
  123. property.SetValue(instance, item.Value.ConvertObject(property.PropertyType));
  124. }
  125. }
  126. break;
  127. }
  128. case IEnumerable<KeyValuePair<string, string>> strs:
  129. {
  130. //处理Cookie
  131. foreach (var item in strs)
  132. {
  133. var property = modelType.GetProperty(item.Key, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
  134. if (property != null)
  135. {
  136. property.SetValue(instance, item.Value.ConvertObject(property.PropertyType));
  137. }
  138. }
  139. break;
  140. }
  141. case IEnumerable<KeyValuePair<string, object>> objects:
  142. {
  143. //处理路由
  144. foreach (var item in objects)
  145. {
  146. var property = modelType.GetProperty(item.Key, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
  147. if (property != null)
  148. {
  149. property.SetValue(instance, item.Value.ConvertObject(property.PropertyType));
  150. }
  151. }
  152. break;
  153. }
  154. }
  155. value = instance;
  156. }
  157. }
  158. }
  159. if (value == null && attr.DefaultValue != null)
  160. {
  161. value = attr.DefaultValue.ChangeType(modelType);
  162. }
  163. }
  164. if (value != null)
  165. {
  166. bindingContext.Result = ModelBindingResult.Success(value);
  167. }
  168. if (exception != null)
  169. {
  170. throw exception;
  171. }
  172. return Task.CompletedTask;
  173. }
  174. private static (IEnumerable data, List<string> keys) GetRequestData(ModelBindingContext bindingContext, Type type)
  175. {
  176. var request = bindingContext.HttpContext.Request;
  177. var props = type.GetProperties().Select(t => t.Name).ToList();
  178. var query = props.Except(request.Query.Keys, StringComparer.OrdinalIgnoreCase).ToList();
  179. var headers = props.Except(request.Headers.Keys, StringComparer.OrdinalIgnoreCase).ToList();
  180. var cookies = props.Except(request.Cookies.Keys, StringComparer.OrdinalIgnoreCase).ToList();
  181. var routes = props.Except(bindingContext.ActionContext.RouteData.Values.Keys, StringComparer.OrdinalIgnoreCase).ToList();
  182. var list = new List<KeyValuePair<List<string>, IEnumerable>>()
  183. {
  184. new(query, request.Query),
  185. new(headers, request.Headers),
  186. new(cookies, request.Cookies),
  187. new(routes, bindingContext.ActionContext.RouteData.Values),
  188. };
  189. if (request.HasFormContentType && request.Form.Count > 0)
  190. {
  191. var forms = props.Except(request.Form.Keys, StringComparer.OrdinalIgnoreCase).ToList();
  192. list.Add(new KeyValuePair<List<string>, IEnumerable>(forms, request.Form));
  193. }
  194. var kv = list.OrderBy(t => t.Key.Count).FirstOrDefault();
  195. return (kv.Value, props.Except(kv.Key).ToList());
  196. }
  197. /// <summary>
  198. /// 获取要绑定的值
  199. /// </summary>
  200. /// <param name="bindingContext"></param>
  201. /// <param name="bindType"></param>
  202. /// <param name="fieldName"></param>
  203. /// <param name="modelType"></param>
  204. private object GetBindingValue(ModelBindingContext bindingContext, BindType bindType, string fieldName, Type modelType)
  205. {
  206. var context = bindingContext.HttpContext;
  207. var mediaType = string.Empty;
  208. if (!string.IsNullOrWhiteSpace(context.Request.ContentType))
  209. {
  210. try
  211. {
  212. var contentType = new ContentType(context.Request.ContentType);
  213. mediaType = contentType.MediaType.ToLower();
  214. }
  215. catch (Exception ex)
  216. {
  217. logger.LogError(ex, "Parsing contentType failed:" + context.Request.ContentType);
  218. mediaType = "multipart/form-data";
  219. }
  220. }
  221. object targetValue = null;
  222. switch (bindType)
  223. {
  224. case BindType.Body:
  225. switch (mediaType)
  226. {
  227. case "application/json":
  228. {
  229. if (bindingContext.HttpContext.Items.TryGetValue("BodyOrDefaultModelBinder@JsonBody", out var obj) && obj is JObject json && json.TryGetValue(fieldName, StringComparison.OrdinalIgnoreCase, out var values))
  230. {
  231. targetValue = values.ConvertObject(modelType);
  232. }
  233. }
  234. break;
  235. case "application/xml":
  236. {
  237. if (bindingContext.HttpContext.Items.TryGetValue("BodyOrDefaultModelBinder@XmlBody", out var obj) && obj is XDocument xml)
  238. {
  239. var xmlElt = xml.Element(fieldName);
  240. if (xmlElt != null)
  241. {
  242. targetValue = xmlElt.Value.ConvertObject(modelType);
  243. }
  244. }
  245. break;
  246. }
  247. }
  248. break;
  249. case BindType.Query:
  250. {
  251. if (context.Request.Query is { Count: > 0 } && context.Request.Query.TryGetValue(fieldName, out var values))
  252. {
  253. targetValue = values.ConvertObject(modelType);
  254. }
  255. }
  256. break;
  257. case BindType.Form:
  258. {
  259. if (context.Request is { HasFormContentType: true, Form.Count: > 0 } && context.Request.Form.TryGetValue(fieldName, out var values))
  260. {
  261. targetValue = values.ConvertObject(modelType);
  262. }
  263. }
  264. break;
  265. case BindType.Header:
  266. {
  267. if (context.Request.Headers is { Count: > 0 } && context.Request.Headers.TryGetValue(fieldName, out var values))
  268. {
  269. targetValue = values.ConvertObject(modelType);
  270. }
  271. }
  272. break;
  273. case BindType.Cookie:
  274. {
  275. if (context.Request.Cookies is { Count: > 0 } && context.Request.Cookies.TryGetValue(fieldName, out var values))
  276. {
  277. targetValue = values.ConvertObject(modelType);
  278. }
  279. }
  280. break;
  281. case BindType.Route:
  282. {
  283. if (bindingContext.ActionContext.RouteData.Values is { Count: > 0 } && bindingContext.ActionContext.RouteData.Values.TryGetValue(fieldName, out var values))
  284. {
  285. targetValue = values.ConvertObject(modelType);
  286. }
  287. }
  288. break;
  289. case BindType.Services:
  290. targetValue = bindingContext.ActionContext.HttpContext.RequestServices.GetRequiredService(modelType);
  291. break;
  292. }
  293. return targetValue;
  294. }
  295. }