Skip to content

Instantly share code, notes, and snippets.

@dbeattie71
Created June 18, 2016 16:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dbeattie71/7820af9f4ae4f68069207b49fc446c94 to your computer and use it in GitHub Desktop.
Save dbeattie71/7820af9f4ae4f68069207b49fc446c94 to your computer and use it in GitHub Desktop.
QueryableExpandAttribute ActionFilterAttribute
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Linq;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace MyDrivingService.Helpers
{
public class QueryableExpandAttribute : ActionFilterAttribute
{
private const string ODataExpandOption = "$expand=";
public QueryableExpandAttribute(string expand)
{
AlwaysExpand = expand;
}
public string AlwaysExpand { get; set; }
public override void OnActionExecuting(HttpActionContext actionContext)
{
base.OnActionExecuting(actionContext);
var request = actionContext.Request;
var query = request.RequestUri.Query.Substring(1);
var parts = query.Split('&').ToList();
var foundExpand = false;
for (int i = 0; i < parts.Count; i++)
{
string segment = parts[i];
if (segment.StartsWith(ODataExpandOption, StringComparison.Ordinal))
{
foundExpand = true;
parts[i] += "," + AlwaysExpand;
break;
}
}
if (!foundExpand)
{
parts.Add(ODataExpandOption + AlwaysExpand);
}
var modifiedRequestUri = new UriBuilder(request.RequestUri)
{
Query = string.Join("&",
parts.Where(p => p.Length > 0))
};
request.RequestUri = modifiedRequestUri.Uri;
base.OnActionExecuting(actionContext);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment