jellyfin/Jellyfin.Api/ModelBinders/NullableEnumModelBinder.cs

48 lines
1.6 KiB
C#
Raw Normal View History

using System;
using System.ComponentModel;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Logging;
2023-01-31 06:18:10 -05:00
namespace Jellyfin.Api.ModelBinders;
/// <summary>
/// Nullable enum model binder.
/// </summary>
public class NullableEnumModelBinder : IModelBinder
{
2023-01-31 06:18:10 -05:00
private readonly ILogger<NullableEnumModelBinder> _logger;
/// <summary>
2023-01-31 06:18:10 -05:00
/// Initializes a new instance of the <see cref="NullableEnumModelBinder"/> class.
/// </summary>
2023-01-31 06:18:10 -05:00
/// <param name="logger">Instance of the <see cref="ILogger{NullableEnumModelBinder}"/> interface.</param>
public NullableEnumModelBinder(ILogger<NullableEnumModelBinder> logger)
{
2023-01-31 06:18:10 -05:00
_logger = logger;
}
2023-01-31 06:18:10 -05:00
/// <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)
{
2023-01-31 06:18:10 -05:00
try
{
2023-01-31 06:18:10 -05:00
// REVIEW: This shouldn't be null here
var convertedValue = converter.ConvertFromString(valueProviderResult.FirstValue!);
bindingContext.Result = ModelBindingResult.Success(convertedValue);
}
catch (FormatException e)
{
_logger.LogDebug(e, "Error converting value.");
}
}
2023-01-31 06:18:10 -05:00
return Task.CompletedTask;
}
2021-02-14 09:11:46 -05:00
}