Skip to content

Instantly share code, notes, and snippets.

@sthewissen
Last active July 23, 2018 05:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sthewissen/9efe2865978a0fe09581 to your computer and use it in GitHub Desktop.
Save sthewissen/9efe2865978a0fe09581 to your computer and use it in GitHub Desktop.
Extension method for getting Route data in ASP.NET MVC Razor pages
public static class RouteDataExtensions
{
// Usage can be seen here: http://www.dvolve.org/2016/01/getting-route-data-in-asp-net-razor/
public static bool Contains(this RouteData route, string action = null, string controller = null, string area = null, StringComparison comparison = StringComparison.CurrentCultureIgnoreCase)
{
// Get the parts that we'll check.
var areaToCheck = route.DataTokens["Area"];
var actionToCheck = route.Values.ContainsKey("Action") ? route.Values["Action"] : null;
var controllerToCheck = route.Values.ContainsKey("Controller") ? route.Values["Controller"] : null;
// No data is provided, so this is always true.
if (controllerToCheck == null && actionToCheck == null && areaToCheck == null) return true;
// Check which pieces match
var actionMatches = string.Equals(action, (string)actionToCheck, comparison) || action == null || action == "*";
var controllerMatches = string.Equals(controller, (string)controllerToCheck, comparison) || controller == null || controller == "*";
var areaResult = string.Equals(area, (string)areaToCheck, comparison) || (area == "" && areaToCheck == null) || area == "*";
// Return the result
return actionMatches && controllerMatches && areaResult;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment