Last active
July 23, 2018 05:02
-
-
Save sthewissen/9efe2865978a0fe09581 to your computer and use it in GitHub Desktop.
Extension method for getting Route data in ASP.NET MVC Razor pages
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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