Skip to content

Instantly share code, notes, and snippets.

@atifaziz
Last active November 24, 2016 10:34
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 atifaziz/f960f7ddd583929057431e168a2aa666 to your computer and use it in GitHub Desktop.
Save atifaziz/f960f7ddd583929057431e168a2aa666 to your computer and use it in GitHub Desktop.
// Derived from https://www.nuget.org/packages/WebPageRouteHandler
using System.Web;
using System.Web.Routing;
using System.Web.WebPages;
public class WebPagesRouteHandler : IRouteHandler
{
readonly string _virtualPath;
Route _routeVirtualPath;
public WebPagesRouteHandler(string virtualPath)
{
_virtualPath = virtualPath;
}
Route RouteVirtualPath =>
_routeVirtualPath
?? (_routeVirtualPath = new Route(_virtualPath.Substring(2), this));
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
var substitutedVirtualPath = GetSubstitutedVirtualPath(requestContext);
var index = substitutedVirtualPath.IndexOf('?');
if (index != -1)
{
substitutedVirtualPath = substitutedVirtualPath.Substring(0, index);
}
requestContext.HttpContext.Items[ContextExtensions.RouteKey] = requestContext.RouteData.Values;
return WebPageHttpHandler.CreateFromVirtualPath(substitutedVirtualPath);
}
public string GetSubstitutedVirtualPath(RequestContext requestContext)
{
var virtualPath = RouteVirtualPath.GetVirtualPath(requestContext, requestContext.RouteData.Values);
return virtualPath == null ? _virtualPath : "~/" + virtualPath.VirtualPath;
}
}
public static class RouteCollectionExtension
{
public static void MapWebPageRoute(this RouteCollection routes, string url, string virtualPath, object defaultValues = null, object constraints = null, string name = null) =>
routes.Add(name ?? url,
new Route(url, new RouteValueDictionary(defaultValues),
new RouteValueDictionary(constraints),
new WebPagesRouteHandler(virtualPath)));
}
public static class ContextExtensions
{
internal const string RouteKey = "__Route";
public static string GetRouteValue(this HttpContextBase context, string key) =>
(context.Items[RouteKey] as RouteValueDictionary)?[key]?.ToString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment