//通过上下文对象得到当前请求的路由表 public MyRouteData GetRouteData(HttpContextBase context) { var MyRouteData = new MyRouteData(); //1.配置RouteHandler实例,这里的RouteHandler是在全局配置里面写进来的 MyRouteData.RouteHandler = MyRoute.RouteHandler; //2.获取当前请求的虚拟路径和说明 var virtualPath = context.Request.AppRelativeCurrentExecutionFilePath.Substring(2) + context.Request.PathInfo; //3.先将默认路由配置写入当前请求的路由表 //每次请求只能读取默认值,而不能覆盖默认值 MyRouteData.RouteValue = new Dictionary <string, object>(); foreach (var key in this.MyRoute.DefaultPath) { MyRouteData.RouteValue[key.Key] = key.Value; } //4.如果当前请求虚拟路径为空,则访问默认路由表。否则从当前请求的url里面去取当前的controller和action的名称 if (!string.IsNullOrEmpty(virtualPath)) { var arrTemplatePath = this.MyRoute.TemplateUrl.Split("{}/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); var arrRealPath = virtualPath.Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); for (var i = 0; i < arrTemplatePath.Length; i++) { var realPath = arrRealPath.Length > i ? arrRealPath[i] : null; if (realPath == null) { break; } MyRouteData.RouteValue[arrTemplatePath[i]] = realPath; } } //5.去读当前请求的参数列表 var querystring = context.Request.QueryString.ToString(); if (string.IsNullOrEmpty(querystring)) { return(MyRouteData); } var parameters = querystring.Split("&".ToArray(), StringSplitOptions.RemoveEmptyEntries); var oparam = new Dictionary <string, string>(); foreach (var parameter in parameters) { var keyvalue = parameter.Split("=".ToArray()); oparam[keyvalue[0]] = keyvalue[1]; } MyRouteData.RouteValue["parameters"] = oparam; return(MyRouteData); }
/// <summary> /// 返回处理当前请求的HttpHandler对象 /// </summary> /// <param name="routeData">当前的请求的路由对象</param> /// <param name="context">当前请求的下文对象</param> /// <returns>处理请求的HttpHandler对象</returns> public System.Web.IHttpHandler GetHttpHandler(MyRouteData routeData, HttpContextBase context) { return(new MyMvcHandler(routeData, context)); }