Skip to content

Instantly share code, notes, and snippets.

@lethek
Last active March 23, 2022 01:13
Show Gist options
  • Save lethek/9613978fa4ee7935bf34f9e68111e990 to your computer and use it in GitHub Desktop.
Save lethek/9613978fa4ee7935bf34f9e68111e990 to your computer and use it in GitHub Desktop.
Check for matching route in ASP.NET MVC 5
using System;
using System.Web;
using System.Web.Routing;
namespace Example
{
public class RouteInfo
{
public RouteInfo(Uri uri, string applicationPath)
=> RouteData = RouteTable.Routes.GetRouteData(new InternalHttpContext(uri, applicationPath));
public RouteData RouteData { get; }
private class InternalHttpContext : HttpContextBase
{
public InternalHttpContext(Uri uri, string applicationPath)
=> Request = new InternalRequestContext(uri, applicationPath);
public override HttpRequestBase Request { get; }
}
private class InternalRequestContext : HttpRequestBase
{
public InternalRequestContext(Uri uri, string applicationPath)
{
PathInfo = uri.Query;
AppRelativeCurrentExecutionFilePath = !String.IsNullOrEmpty(applicationPath) && !uri.AbsolutePath.StartsWith(applicationPath, StringComparison.OrdinalIgnoreCase)
? String.Concat("~", uri.AbsolutePath.Substring(applicationPath.Length))
: String.Concat("~", uri.AbsolutePath);
}
public override string PathInfo { get; }
public override string AppRelativeCurrentExecutionFilePath { get; }
}
}
}
using System;
using System.Web;
using System.Web.Routing;
namespace Example
{
public static class UriExtensions
{
public static bool IsRouteMatch(this Uri uri, string controllerName, string actionName)
{
var routeInfo = new RouteInfo(uri, HttpContext.Current.Request.ApplicationPath);
return (
routeInfo.RouteData.Values["controller"].ToString() == controllerName &&
routeInfo.RouteData.Values["action"].ToString() == actionName
);
}
public static bool IsRouteMatch(this Uri uri, string controllerName, string actionName, string areaName)
{
var routeInfo = new RouteInfo(uri, HttpContext.Current.Request.ApplicationPath);
return (
routeInfo.RouteData.Values["controller"].ToString() == controllerName &&
routeInfo.RouteData.Values["action"].ToString() == actionName &&
routeInfo.RouteData.DataTokens["area"].ToString() == areaName
);
}
public static string GetRouteDataValue(this Uri uri, string parameterName)
{
var routeInfo = new RouteInfo(uri, HttpContext.Current.Request.ApplicationPath);
return routeInfo.RouteData.Values[parameterName] != null
? routeInfo.RouteData.Values[parameterName].ToString()
: null;
}
public static RouteData ToRouteData(this Uri uri)
=> new RouteInfo(uri, HttpContext.Current.Request.ApplicationPath).RouteData;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment