Asp.Net webpages 扩展自定义路由,满足各类需求 WebPageRouteHandler.cs
一、使用方法
1、_AppStart.cshtml 设置路由
RouteTable.Routes.MapWebPageRoute("{url}.html", "~/webCity.cshtml", new { url = "" });
这个大家可以自由发挥,根据自己实际需求。
2、webCity.cshtml 获取参数
var urls = Context.GetRouteValue("url");
就这么简单。
3、WebPageRouteHandler.cs 核心代码
这个文件嘛,根据自己去修改吧,我做简单的网站不太喜欢用命名空间。
文件放在App_Code目录下
二、文件代码
1 using System; 2 using System.Globalization; 3 using System.Web; 4 using System.Web.Routing; 5 using System.Web.WebPages; 6 7 public class WebPagesRouteHandler : IRouteHandler { 8 private readonly string _virtualPath; 9 private Route _routeVirtualPath; 10 11 public WebPagesRouteHandler(string virtualPath) { 12 _virtualPath = virtualPath; 13 } 14 15 private Route RouteVirtualPath { 16 get { 17 if (_routeVirtualPath == null) { 18 _routeVirtualPath = new Route(_virtualPath.Substring(2), this); 19 } 20 return this._routeVirtualPath; 21 } 22 } 23 24 public IHttpHandler GetHttpHandler(RequestContext requestContext) { 25 var substitutedVirtualPath = GetSubstitutedVirtualPath(requestContext); 26 int index = substitutedVirtualPath.IndexOf('?'); 27 if (index != -1) { 28 substitutedVirtualPath = substitutedVirtualPath.Substring(0, index); 29 } 30 requestContext.HttpContext.Items[ContextExtensions.RouteKey] = requestContext.RouteData.Values; 31 return WebPageHttpHandler.CreateFromVirtualPath(substitutedVirtualPath); 32 } 33 34 public string GetSubstitutedVirtualPath(RequestContext requestContext) { 35 VirtualPathData virtualPath = RouteVirtualPath.GetVirtualPath(requestContext, requestContext.RouteData.Values); 36 if (virtualPath == null) { 37 return _virtualPath; 38 } 39 return ("~/" + virtualPath.VirtualPath); 40 } 41 } 42 43 public static class RouteCollectionExtension { 44 public static void MapWebPageRoute(this RouteCollection routeCollection, string routeUrl, string virtualPath, object defaultValues = null, object constraints = null, string routeName = null) { 45 routeName = routeName ?? routeUrl; 46 47 Route item = new Route(routeUrl, new RouteValueDictionary(defaultValues), new RouteValueDictionary(constraints), new WebPagesRouteHandler(virtualPath)); 48 routeCollection.Add(routeName, item); 49 } 50 } 51 52 public static class ContextExtensions { 53 internal const string RouteKey = "__Route"; 54 public static string GetRouteValue(this HttpContextBase context, string key) { 55 var route = context.Items[RouteKey] as RouteValueDictionary; 56 if (route != null) { 57 var routeValue = route[key]; 58 return routeValue != null ? routeValue.ToString() : null; 59 } 60 return null; 61 } 62 }
具体代码就不解释了。不明白的朋友可以在评论区留言。