The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

FormDataJsonBinder.cs 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. using Microsoft.AspNetCore.Mvc.ModelBinding;
  2. using Newtonsoft.Json;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace Teknik.Utilities
  8. {
  9. public class FormDataJsonBinder : IModelBinder
  10. {
  11. public Task BindModelAsync(ModelBindingContext bindingContext)
  12. {
  13. if (bindingContext == null) throw new ArgumentNullException(nameof(bindingContext));
  14. // Fetch the value of the argument by name and set it to the model state
  15. string fieldName = bindingContext.FieldName;
  16. var valueProviderResult = bindingContext.ValueProvider.GetValue(fieldName);
  17. if (valueProviderResult == ValueProviderResult.None) return Task.CompletedTask;
  18. else bindingContext.ModelState.SetModelValue(fieldName, valueProviderResult);
  19. // Do nothing if the value is null or empty
  20. string value = valueProviderResult.FirstValue;
  21. if (string.IsNullOrEmpty(value)) return Task.CompletedTask;
  22. try
  23. {
  24. // Deserialize the provided value and set the binding result
  25. object result = JsonConvert.DeserializeObject(value, bindingContext.ModelType);
  26. bindingContext.Result = ModelBindingResult.Success(result);
  27. }
  28. catch (JsonException)
  29. {
  30. bindingContext.Result = ModelBindingResult.Failed();
  31. }
  32. return Task.CompletedTask;
  33. }
  34. }
  35. }