FromBodyOrDefaultModelBinder.cs 8.4 KB

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