using System;
using System.ComponentModel;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Logging;
namespace Jellyfin.Api.ModelBinders
{
///
/// Nullable enum model binder.
///
public class NullableEnumModelBinder : IModelBinder
{
private readonly ILogger _logger;
///
/// Initializes a new instance of the class.
///
/// Instance of the interface.
public NullableEnumModelBinder(ILogger logger)
{
_logger = logger;
}
///
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.LogWarning(e, "Error converting value.");
}
}
return Task.CompletedTask;
}
}
}