using System.Collections.Generic; using System.Text.RegularExpressions; using System.Threading.Tasks; using Luticate2.Utils.Dbo.Result; using Microsoft.AspNetCore.Mvc.ModelBinding; namespace Luticate2.Utils.Dbo.Filter { public class LuFilterBinder : IModelBinder { private const string RegExp = "^([\\w\\-]+) *: *([^ \"\']+|\"[^\"]+\"|\'[^\']+\') *"; public static LuResult FromString(string data) { if (data == null) { data = ""; } var filters = new Dictionary(); Match match; do { match = Regex.Match(data, RegExp); if (match.Success) { var value = match.Groups[2].Value; if ((value.StartsWith("\"") && value.EndsWith("\"")) || (value.StartsWith("\'") && value.EndsWith("\'"))) { value = value.Remove(value.Length - 1, 1).Remove(0, 1); } filters.Add(match.Groups[1].Value, value); data = data.Remove(match.Index, match.Length); } } while (match.Success); var dbo = new LuFilterDbo { Query = data.Trim(), Filters = filters }; return LuResult.Ok(dbo); } public Task BindModelAsync(ModelBindingContext bindingContext) { var messageTypeResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); var res = FromString(messageTypeResult.FirstValue); if (res) { bindingContext.Result = ModelBindingResult.Success(res.Data); } else { bindingContext.Result = ModelBindingResult.Failed(); } return Task.FromResult(0); } } public class LuFilterBinderProvider : IModelBinderProvider { public IModelBinder GetBinder(ModelBinderProviderContext context) { if (context.Metadata.ModelType == typeof(LuFilterDbo)) { return new LuFilterBinder(); } return null; } } }