using System;
using System.Web.Routing;
using System.Web;
namespace RouteDebug
{
public class DebugHttpHandler : IHttpHandler
{
public RequestContext RequestContext { get; set; }
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
string htmlFormat = @"
Route Tester
Route Tester
Type in a url in the address bar to see which defined routes match it.
A {{*catchall}} route is added to the list of routes automatically in
case none of your routes match.
Route : {1}
All Routes
Matches Current Request
Url
Defaults
Constraints
DataTokens
{2}
";
string routeDataRows = string.Empty;
RouteData routeData = this.RequestContext.RouteData;
RouteValueDictionary routeValues = routeData.Values;
RouteBase matchedRouteBase = routeData.Route;
string routes = string.Empty;
using (RouteTable.Routes.GetReadLock())
{
foreach (RouteBase routeBase in RouteTable.Routes)
{
bool matchesCurrentRequest = (routeBase.GetRouteData(RequestContext.HttpContext) != null);
string matchText = string.Format(@"{0} ", matchesCurrentRequest);
string url = "n/a";
string defaults = "n/a";
string constraints = "n/a";
string dataTokens = "n/a";
Route route = routeBase as Route;
if (route != null)
{
url = route.Url;
defaults = FormatRouteValueDictionary(route.Defaults);
constraints = FormatRouteValueDictionary(route.Constraints);
dataTokens = FormatRouteValueDictionary(route.DataTokens);
}
routes += string.Format(@"{0} {1} {2} {3} {3} "
, matchText
, url
, defaults
, constraints
, dataTokens);
}
}
string matchedRouteUrl = "n/a";
if (!(matchedRouteBase is DebugRoute))
{
foreach (string key in routeValues.Keys)
{
routeDataRows += string.Format("\t{0} {1} ", key, routeValues[key]);
}
Route matchedRoute = matchedRouteBase as Route;
if (matchedRoute != null)
matchedRouteUrl = matchedRoute.Url;
}
else
{
matchedRouteUrl = "NO MATCH! ";
}
context.Response.Write(string.Format(htmlFormat
, routeDataRows
, matchedRouteUrl
, routes));
}
private static string FormatRouteValueDictionary(RouteValueDictionary values)
{
if (values == null)
return "(null)";
string display = string.Empty;
foreach (string key in values.Keys)
display += string.Format("{0} = {1}, ", key, values[key]);
if (display.EndsWith(", "))
display = display.Substring(0, display.Length - 2);
return display;
}
}
}