-
Notifications
You must be signed in to change notification settings - Fork 549
Expand file tree
/
Copy pathEnableQueryAttribute.cs
More file actions
48 lines (39 loc) · 1.68 KB
/
Copy pathEnableQueryAttribute.cs
File metadata and controls
48 lines (39 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using System.Linq.Dynamic.Core;
using Microsoft.AspNetCore.Http;
using Grand.Module.Api.Constants;
namespace Grand.Module.Api.Attributes;
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class EnableQueryAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext context)
{
if (context.Result is not ObjectResult result || result.Value == null)
return;
if (result.Value is IQueryable queryable)
{
queryable = ApplyQueryOptions(queryable, context.HttpContext.Request.Query, context.HttpContext.Response);
result.Value = queryable;
}
}
private static IQueryable ApplyQueryOptions(IQueryable queryable, IQueryCollection query, HttpResponse response)
{
if (query.TryGetValue("$filter", out var filter))
queryable = queryable.Where(filter.ToString());
if (query.TryGetValue("$orderby", out var orderBy))
queryable = queryable.OrderBy(orderBy.ToString());
if (query.TryGetValue("$select", out var select))
queryable = queryable.Select($"new({select})");
if (query.TryGetValue("$skip", out var skipValue) && int.TryParse(skipValue, out var skip))
queryable = queryable.Skip(skip);
if (query.TryGetValue("$top", out var topValue) && int.TryParse(topValue, out var top))
{
top = Math.Min(top, Configurations.MaxLimit);
queryable = queryable.Take(top);
}
else
queryable = queryable.Take(Configurations.MaxLimit);
return queryable;
}
}