JsonModelBinder.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using System;
  2. using System.IO;
  3. using System.Threading.Tasks;
  4. using Microsoft.AspNetCore.Mvc.ModelBinding;
  5. using Newtonsoft.Json;
  6. namespace ZR.Common.DynamicApiSimple;
  7. public class JsonModelBinder : IModelBinder
  8. {
  9. private readonly IModelBinder _fallbackBinder;
  10. public JsonModelBinder(IModelBinder fallbackBinder)
  11. {
  12. _fallbackBinder = fallbackBinder;
  13. }
  14. public async Task BindModelAsync(ModelBindingContext bindingContext)
  15. {
  16. if (bindingContext == null)
  17. {
  18. throw new ArgumentNullException(nameof(bindingContext));
  19. }
  20. var request = bindingContext.HttpContext.Request;
  21. if ((request.Method == "POST" || request.Method == "PUT") && request.ContentType != null && request.ContentType.Contains("application/json"))
  22. {
  23. using (var reader = new StreamReader(request.Body))
  24. {
  25. var body = await reader.ReadToEndAsync();
  26. if (!string.IsNullOrEmpty(body))
  27. {
  28. var result = JsonConvert.DeserializeObject(body, bindingContext.ModelType);
  29. bindingContext.Result = ModelBindingResult.Success(result);
  30. return;
  31. }
  32. }
  33. }
  34. if (_fallbackBinder != null)
  35. {
  36. await _fallbackBinder.BindModelAsync(bindingContext);
  37. }
  38. else
  39. {
  40. bindingContext.Result = ModelBindingResult.Failed();
  41. }
  42. }
  43. }