开发者

Can I get the controller from the HttpContext?

开发者 https://www.devze.com 2023-02-17 05:42 出处:网络
Given an HttpContext (or HttpContextBase), is there a way to get an instance of the Controller?开发者_JS百科For those looking just to get the controller name and not an actual instance, as is needed f

Given an HttpContext (or HttpContextBase), is there a way to get an instance of the Controller?开发者_JS百科


For those looking just to get the controller name and not an actual instance, as is needed for custom authorization overrides of AuthorizeCore(httpContext), this is the clean code.

var request = httpContext.Request;
var currentUser = httpContext.User.Identity.Name;
string controller = request.RequestContext.RouteData.Values["controller"].ToString();
string action = request.RequestContext.RouteData.Values["action"].ToString();


The HttpContext will hold a reference to the MvcHandler, which will hold a reference to the RouteData, which will hold a reference to what controller is being invoked by a particular route.

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;
        }
    }
}

This code may look familiar, it's because I've adapted it from Phil Haack's route debugger source code.


var currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext));
var currentController = currentRouteData.Values["controller"].ToString();
var currentAction = currentRouteData.Values["action"].ToString();


Not easily, you will basically have to first get the MvcHandler from the RouteData, then build the Controller. Even then, it won't give you the instance used to handle the action as it will be a new instance of the controller.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号