aboutsummaryrefslogtreecommitdiff
path: root/Jellyfin.Api/ModelBinders
diff options
context:
space:
mode:
authorgithub@esslinger.dev <simon@esslinger.dev>2020-10-01 19:56:59 +0200
committergithub@esslinger.dev <simon@esslinger.dev>2020-10-01 19:56:59 +0200
commit0655928ab14452dde97192ead66b33c927a75d5a (patch)
tree1b91a8563618248d0b9ceaf286ce567f59d67e62 /Jellyfin.Api/ModelBinders
parentf314be9d8513829a5de21eeb2ef19e10943b2a0e (diff)
feat: add CommaDelimitedArrayModelBinder
Diffstat (limited to 'Jellyfin.Api/ModelBinders')
-rw-r--r--Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs42
1 files changed, 42 insertions, 0 deletions
diff --git a/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs b/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs
new file mode 100644
index 000000000..1bfd741fd
--- /dev/null
+++ b/Jellyfin.Api/ModelBinders/CommaDelimitedArrayModelBinder.cs
@@ -0,0 +1,42 @@
+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 input = valueProviderResult.FirstValue;
+ var elementType = bindingContext.ModelType.GetElementType();
+
+ if (input != null)
+ {
+ var converter = TypeDescriptor.GetConverter(elementType);
+ var values = Array.ConvertAll(
+ input.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries),
+ x => { return converter.ConvertFromString(x != null ? x.Trim() : x); });
+
+ 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;
+ }
+ }
+}