-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathLinqToQueryableAttribute.cs
More file actions
60 lines (50 loc) · 2.36 KB
/
LinqToQueryableAttribute.cs
File metadata and controls
60 lines (50 loc) · 2.36 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
49
50
51
52
53
54
55
56
57
58
59
60
namespace LinqToQuerystring.WebApi
{
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Web;
using System.Web.Http.Filters;
using ActionFilterAttribute = System.Web.Http.Filters.ActionFilterAttribute;
public class LinqToQueryableAttribute : ActionFilterAttribute
{
private readonly bool forceDynamicProperties;
private readonly int maxPageSize;
public LinqToQueryableAttribute(bool forceDynamicProperties = false, int maxPageSize = -1)
{
this.forceDynamicProperties = forceDynamicProperties;
this.maxPageSize = maxPageSize;
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
object responseObject;
actionExecutedContext.Response.TryGetContentValue(out responseObject);
var originalquery = responseObject as IQueryable;
if (originalquery != null)
{
var queryString = HttpUtility.UrlDecode(actionExecutedContext.Request.RequestUri.Query);
var genericType = originalquery.GetType().GetGenericArguments()[0];
var reply = originalquery.LinqToQuerystring(genericType, queryString, this.forceDynamicProperties, this.maxPageSize);
var replyType = reply.GetType();
if (typeof(IQueryable).IsAssignableFrom(replyType))
{
var queryableType = typeof(IQueryable<>).GetGenericTypeDefinition();
var genericArgs = replyType.GetGenericArguments();
replyType = queryableType.MakeGenericType(genericArgs);
}
var configuraton = actionExecutedContext.ActionContext.ControllerContext.Configuration;
var conneg = (IContentNegotiator)configuraton.Services.GetService(typeof(IContentNegotiator));
var formatter = conneg.Negotiate(
replyType,
actionExecutedContext.Request,
configuraton.Formatters);
actionExecutedContext.Response = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new ObjectContent(replyType, reply, formatter.Formatter)
};
}
}
}
}