2020-11-21 11:58:35 -07:00
|
|
|
|
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
|
|
|
|
|
{
|
2021-02-14 07:11:46 -07:00
|
|
|
|
// REVIEW: This shouldn't be null here
|
|
|
|
|
var convertedValue = converter.ConvertFromString(valueProviderResult.FirstValue!);
|
2020-11-21 11:58:35 -07:00
|
|
|
|
bindingContext.Result = ModelBindingResult.Success(convertedValue);
|
|
|
|
|
}
|
|
|
|
|
catch (FormatException e)
|
|
|
|
|
{
|
2021-01-01 09:34:39 -07:00
|
|
|
|
_logger.LogDebug(e, "Error converting value.");
|
2020-11-21 11:58:35 -07:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return Task.CompletedTask;
|
|
|
|
|
}
|
|
|
|
|
}
|
2021-02-14 07:11:46 -07:00
|
|
|
|
}
|