BodyAndQueryModelBinder.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. using Microsoft.AspNetCore.Mvc.ModelBinding;
  2. using Newtonsoft.Json;
  3. using System.IO;
  4. using System.Threading.Tasks;
  5. using System.Web;
  6. using System;
  7. using System.Linq;
  8. namespace Masuit.Tools.Core.AspNetCore;
  9. public class BodyAndQueryModelBinder<T> : IModelBinder where T : IConvertible
  10. {
  11. public async Task BindModelAsync(ModelBindingContext bindingContext)
  12. {
  13. var body = bindingContext.HttpContext.Request.Body;
  14. using var reader = new StreamReader(body);
  15. var text = await reader.ReadToEndAsync();
  16. if (typeof(T).IsPrimitive || typeof(T) == typeof(string) || typeof(T).IsEnum || typeof(T) == typeof(DateTime) || typeof(T) == typeof(Guid))
  17. {
  18. bindingContext.Result = ModelBindingResult.Success(JsonConvert.DeserializeObject<T>(text) ?? bindingContext.HttpContext.Request.Query[bindingContext.ModelMetadata.ParameterName!].ToString().ConvertTo<T>());
  19. return;
  20. }
  21. var dict = HttpUtility.ParseQueryString(bindingContext.HttpContext.Request.QueryString.ToString());
  22. var contract = JsonConvert.DeserializeObject<T>(text) ?? JsonConvert.DeserializeObject<T>(dict.Cast<string>().ToDictionary(k => k, k => dict[k]).ToJsonString());
  23. var properties = typeof(T).GetProperties();
  24. foreach (var property in properties)
  25. {
  26. var valueProvider = bindingContext.ValueProvider.GetValue(property.Name);
  27. if (string.IsNullOrEmpty(valueProvider.FirstValue))
  28. {
  29. property.SetValue(contract, valueProvider.FirstValue);
  30. }
  31. }
  32. bindingContext.Result = ModelBindingResult.Success(contract);
  33. }
  34. }