-
Notifications
You must be signed in to change notification settings - Fork 5
/
QueryableExpandAttribute.cs
46 lines (40 loc) · 1.4 KB
/
QueryableExpandAttribute.cs
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
using System;
using System.Linq;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
public class QueryableExpandAttribute : ActionFilterAttribute
{
private const string ODataExpandOption = "$expand=";
public QueryableExpandAttribute(string expand)
{
this.AlwaysExpand = expand;
}
public string AlwaysExpand { get; set; }
public override void OnActionExecuting(HttpActionContext actionContext)
{
HttpRequestMessage request = actionContext.Request;
string query = request.RequestUri.Query.Substring(1);
var parts = query.Split('&').ToList();
bool foundExpand = false;
for (int i = 0; i < parts.Count; i++)
{
string segment = parts[i];
if (segment.StartsWith(ODataExpandOption, StringComparison.Ordinal))
{
foundExpand = true;
parts[i] += "," + this.AlwaysExpand;
break;
}
}
if (!foundExpand)
{
parts.Add(ODataExpandOption + this.AlwaysExpand);
}
UriBuilder modifiedRequestUri = new UriBuilder(request.RequestUri);
modifiedRequestUri.Query = string.Join("&",
parts.Where(p => p.Length > 0));
request.RequestUri = modifiedRequestUri.Uri;
base.OnActionExecuting(actionContext);
}
}