Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 key = match.Groups[1].Value;
  25. var value = match.Groups[2].Value;
  26. if ((value.StartsWith("\"") && value.EndsWith("\"")) ||
  27. (value.StartsWith("\'") && value.EndsWith("\'")))
  28. {
  29. value = value.Remove(value.Length - 1, 1).Remove(0, 1).Trim();
  30. }
  31. if (!filters.ContainsKey(key))
  32. {
  33. filters.Add(key, value);
  34. }
  35. else
  36. {
  37. filters[key] = value;
  38. }
  39. data = data.Remove(match.Index, match.Length);
  40. }
  41. } while (match.Success);
  42. var dbo = new LuFilterDbo
  43. {
  44. Query = data.Trim(),
  45. Filters = filters
  46. };
  47. return LuResult<LuFilterDbo>.Ok(dbo);
  48. }
  49. public Task BindModelAsync(ModelBindingContext bindingContext)
  50. {
  51. var messageTypeResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
  52. var res = FromString(messageTypeResult.FirstValue);
  53. if (res)
  54. {
  55. bindingContext.Result = ModelBindingResult.Success(res.Data);
  56. }
  57. else
  58. {
  59. bindingContext.Result = ModelBindingResult.Failed();
  60. }
  61. return Task.FromResult(0);
  62. }
  63. }
  64. public class LuFilterBinderProvider : IModelBinderProvider
  65. {
  66. public IModelBinder GetBinder(ModelBinderProviderContext context)
  67. {
  68. if (context.Metadata.ModelType == typeof(LuFilterDbo))
  69. {
  70. return new LuFilterBinder();
  71. }
  72. return null;
  73. }
  74. }
  75. }