Last active
November 24, 2016 10:34
-
-
Save atifaziz/f960f7ddd583929057431e168a2aa666 to your computer and use it in GitHub Desktop.
Derived from https://www.nuget.org/packages/WebPageRouteHandler
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
// 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