NullableEnumModelBinder.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System;
  2. using System.ComponentModel;
  3. using System.Threading.Tasks;
  4. using Microsoft.AspNetCore.Mvc.ModelBinding;
  5. using Microsoft.Extensions.Logging;
  6. namespace Jellyfin.Api.ModelBinders
  7. {
  8. /// <summary>
  9. /// Nullable enum model binder.
  10. /// </summary>
  11. public class NullableEnumModelBinder : IModelBinder
  12. {
  13. private readonly ILogger<NullableEnumModelBinder> _logger;
  14. /// <summary>
  15. /// Initializes a new instance of the <see cref="NullableEnumModelBinder"/> class.
  16. /// </summary>
  17. /// <param name="logger">Instance of the <see cref="ILogger{NullableEnumModelBinder}"/> interface.</param>
  18. public NullableEnumModelBinder(ILogger<NullableEnumModelBinder> logger)
  19. {
  20. _logger = logger;
  21. }
  22. /// <inheritdoc />
  23. public Task BindModelAsync(ModelBindingContext bindingContext)
  24. {
  25. var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
  26. var elementType = bindingContext.ModelType.GetElementType() ?? bindingContext.ModelType.GenericTypeArguments[0];
  27. var converter = TypeDescriptor.GetConverter(elementType);
  28. if (valueProviderResult.Length != 0)
  29. {
  30. try
  31. {
  32. var convertedValue = converter.ConvertFromString(valueProviderResult.FirstValue);
  33. bindingContext.Result = ModelBindingResult.Success(convertedValue);
  34. }
  35. catch (FormatException e)
  36. {
  37. _logger.LogDebug(e, "Error converting value.");
  38. }
  39. }
  40. return Task.CompletedTask;
  41. }
  42. }
  43. }