diff options
| author | Bond-009 <bond.009@outlook.com> | 2020-10-04 22:40:14 +0200 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2020-10-04 22:40:14 +0200 |
| commit | 07be0661802106bf9c003d75b76f5977497e8094 (patch) | |
| tree | 777ce1983a56064b0df088d3d4ad4054c49e4b5a /Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs | |
| parent | d11adeb85ee82c3699f5a3a2e4f660623a19df78 (diff) | |
| parent | ec0ff5d02fa53ca5b902d0bd5b477199170f3d28 (diff) | |
Merge pull request #4252 from skyfrk/4214-supported-commands-enum
Convert supportedCommands strings to enums
Diffstat (limited to 'Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs')
| -rw-r--r-- | Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs b/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs new file mode 100644 index 000000000..13469194a --- /dev/null +++ b/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs @@ -0,0 +1,64 @@ +using System; +using System.ComponentModel; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc.ModelBinding; + +namespace Jellyfin.Api.ModelBinders +{ + /// <summary> + /// Comma delimited array model binder. + /// Returns an empty array of specified type if there is no query parameter. + /// </summary> + public class CommaDelimitedArrayModelBinder : IModelBinder + { + /// <inheritdoc/> + public Task BindModelAsync(ModelBindingContext bindingContext) + { + var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); + var elementType = bindingContext.ModelType.GetElementType(); + var converter = TypeDescriptor.GetConverter(elementType); + + if (valueProviderResult == ValueProviderResult.None) + { + return Task.CompletedTask; + } + + if (valueProviderResult.Length > 1) + { + var result = Array.CreateInstance(elementType, valueProviderResult.Length); + + for (int i = 0; i < valueProviderResult.Length; i++) + { + var value = converter.ConvertFromString(valueProviderResult.Values[i].Trim()); + + result.SetValue(value, i); + } + + bindingContext.Result = ModelBindingResult.Success(result); + } + else + { + var value = valueProviderResult.FirstValue; + + if (value != null) + { + var values = Array.ConvertAll( + value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries), + x => converter.ConvertFromString(x?.Trim())); + + var typedValues = Array.CreateInstance(elementType, values.Length); + values.CopyTo(typedValues, 0); + + bindingContext.Result = ModelBindingResult.Success(typedValues); + } + else + { + var emptyResult = Array.CreateInstance(elementType, 0); + bindingContext.Result = ModelBindingResult.Success(emptyResult); + } + } + + return Task.CompletedTask; + } + } +} |
