Determining which controller and action is handling a particular URL in ASP.NET MVC

Something like this for controller:

string controller = RouteData.GetRequiredString("controller");

And for action:

string action = RouteData.GetRequiredString("action");

For example you can use it in your base controller class:

    public class YouControllerBase: Controller
    {
          protected override void Execute(System.Web.Routing.RequestContext requestContext)
          {
              string controller = requestContext.RouteData.GetRequiredString("controller");
              string action = requestContext.RouteData.GetRequiredString("action");
          }
   }

Or use it in global.asax:

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        RouteData routeData = RouteTable.Routes.GetRouteData(
            new HttpContextWrapper(HttpContext.Current));
        var action = routeData.GetRequiredString("action");
    }

You could try this ASP.NET Routing Debugger:

alt text
(source: haacked.com)


pete,

in code, you can use an actionfilter to determine whats going on:

public class AddUrlInfoToSessionAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (!filterContext.HttpContext.Request.IsAjaxRequest())
        {
            // where we are now - do something with the vars in real app
            var currentActionName = filterContext.ActionDescriptor.ActionName;
            var currentControllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            var currentRouteData = filterContext.RouteData;
            var currentUrlInfo = new UrlHelper(filterContext.RequestContext);
            string url = RouteTable.Routes.GetVirtualPath(filterContext.RequestContext, currentRouteData.Values).VirtualPath;
        }
    }
}

and then decorate each controller that your interested in as below (or put it onto a basecontroller):

[HandleError]
[AddUrlInfoToSessionAttribute]
public class HomeController : Controller
{
    // controller stuff
}

[AddUrlInfoToSession]
public abstract class BaseController : Controller
{

}

hope this helps

jim

EDIT: just tidied the example up a bit by adding the following to the filter method:

string url = RouteTable.Routes.GetVirtualPath(filterContext.RequestContext, currentRouteData.Values).VirtualPath;

Tags:

Asp.Net Mvc