1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- 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<LuFilterDbo> FromString(string data)
- {
- if (data == null)
- {
- data = "";
- }
- var filters = new Dictionary<string, string>();
-
- 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<LuFilterDbo>.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;
- }
- }
- }
|