You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LuFilterBinder.cs 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System.Collections.Generic;
  2. using System.Text.RegularExpressions;
  3. using System.Threading.Tasks;
  4. using Luticate2.Utils.Dbo.Result;
  5. using Microsoft.AspNetCore.Mvc.ModelBinding;
  6. namespace Luticate2.Utils.Dbo.Filter
  7. {
  8. public class LuFilterBinder : IModelBinder
  9. {
  10. private const string RegExp = "^([\\w\\-]+) *: *([^ \"\']+|\"[^\"]+\"|\'[^\']+\') *";
  11. public static LuResult<LuFilterDbo> FromString(string data)
  12. {
  13. if (data == null)
  14. {
  15. data = "";
  16. }
  17. var filters = new Dictionary<string, string>();
  18. Match match;
  19. do
  20. {
  21. match = Regex.Match(data, RegExp);
  22. if (match.Success)
  23. {
  24. var value = match.Groups[2].Value;
  25. if ((value.StartsWith("\"") && value.EndsWith("\"")) ||
  26. (value.StartsWith("\'") && value.EndsWith("\'")))
  27. {
  28. value = value.Remove(value.Length - 1, 1).Remove(0, 1);
  29. }
  30. filters.Add(match.Groups[1].Value, value);
  31. data = data.Remove(match.Index, match.Length);
  32. }
  33. } while (match.Success);
  34. var dbo = new LuFilterDbo
  35. {
  36. Query = data.Trim(),
  37. Filters = filters
  38. };
  39. return LuResult<LuFilterDbo>.Ok(dbo);
  40. }
  41. public Task BindModelAsync(ModelBindingContext bindingContext)
  42. {
  43. var messageTypeResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
  44. var res = FromString(messageTypeResult.FirstValue);
  45. if (res)
  46. {
  47. bindingContext.Result = ModelBindingResult.Success(res.Data);
  48. }
  49. else
  50. {
  51. bindingContext.Result = ModelBindingResult.Failed();
  52. }
  53. return Task.FromResult(0);
  54. }
  55. }
  56. public class LuFilterBinderProvider : IModelBinderProvider
  57. {
  58. public IModelBinder GetBinder(ModelBinderProviderContext context)
  59. {
  60. if (context.Metadata.ModelType == typeof(LuFilterDbo))
  61. {
  62. return new LuFilterBinder();
  63. }
  64. return null;
  65. }
  66. }
  67. }