asp.net-mvc – 我可以从HttpContext获取控制器吗?

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 我可以从HttpContext获取控制器吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
给定一个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代码

原文链接:https://www.f2er.com/aspnet/254520.html

猜你在找的asp.Net相关文章