给定一个HttpContext(或HttpContextBase),有没有办法获得一个Controller的实例?
解决方法
HttpContext将保存对MvcHandler的引用,该引用将保存对RouteData的引用,该引用将保存对特定路由正在调用什么控制器的引用。
NB: This doesn’t give you the actual controller,only the controller
that the specific route is going to
catch.
GetController(HttpContextBase httpContext) { var routeData = ((MvcHandler)httpContext.Handler).RequestContext.RouteData; var routeValues = routeData.Values; var matchedRouteBase = routeData.Route; var matchedRoute = matchedRouteBase as Route; if (matchedRoute != null) { Route = matchedRoute.Url ?? string.Empty; } AssignRouteValues(httpContext,routeValues); } protected virtual VirtualPathData getVirtualPathData(HttpContextBase httpContext,RouteValueDictionary routeValues) { return RouteTable.Routes.GetVirtualPath(((MvcHandler)httpContext.Handler).RequestContext,routeValues); } private void AssignRouteValues(HttpContextBase httpContext,RouteValueDictionary routeValues) { var virtualPathData = getVirtualPathData(httpContext,routeValues); if (virtualPathData != null) { var vpdRoute = virtualPathData.Route as Route; if (vpdRoute != null) { RouteDefaults = vpdRoute.Defaults; RouteConstraints = vpdRoute.Constraints; RouteDataTokens = virtualPathData.DataTokens; RouteValues = routeValues; } } }
这段代码可能看起来很熟悉,这是因为我已经适应了Phil Haack的route debugger源代码。