aboutsummaryrefslogtreecommitdiff
path: root/Jellyfin.Api/ModelBinders/NullableEnumModelBinder.cs
blob: be2045fbabcd4e38f2c77c689f8958dba6cd1ac2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using System;
using System.ComponentModel;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Logging;

namespace Jellyfin.Api.ModelBinders
{
    /// <summary>
    /// Nullable enum model binder.
    /// </summary>
    public class NullableEnumModelBinder : IModelBinder
    {
        private readonly ILogger<NullableEnumModelBinder> _logger;

        /// <summary>
        /// Initializes a new instance of the <see cref="NullableEnumModelBinder"/> class.
        /// </summary>
        /// <param name="logger">Instance of the <see cref="ILogger{NullableEnumModelBinder}"/> interface.</param>
        public NullableEnumModelBinder(ILogger<NullableEnumModelBinder> logger)
        {
            _logger = logger;
        }

        /// <inheritdoc />
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            var elementType = bindingContext.ModelType.GetElementType() ?? bindingContext.ModelType.GenericTypeArguments[0];
            var converter = TypeDescriptor.GetConverter(elementType);
            if (valueProviderResult.Length != 0)
            {
                try
                {
                    var convertedValue = converter.ConvertFromString(valueProviderResult.FirstValue);
                    bindingContext.Result = ModelBindingResult.Success(convertedValue);
                }
                catch (FormatException e)
                {
                    _logger.LogDebug(e, "Error converting value.");
                }
            }

            return Task.CompletedTask;
        }
    }
}