Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

asp.net-mvc

Given a particular URL, how do I find out for sure which controller action it is being routed to (perhaps in the context of a large application with many controllers and a complex route registry)?

I'm not asking how to configure routes.

like image 458
Pete Montgomery Avatar asked Apr 14 '10 08:04

Pete Montgomery


People also ask

How are URL patterns mapped to a handler in ASP.NET MVC?

Typical URL Patterns in MVC Applications URL patterns for routes in MVC Applications typically include {controller} and {action} placeholders. When a request is received, it is routed to the UrlRoutingModule object and then to the MvcHandler HTTP handler.

Which action is invoked when we call any controller?

Every controller can have a default action method as per the configured route in the RouteConfig class. By default, the Index() method is a default action method for any controller, as per configured default root, as shown below.

How do I find the base URL of a controller?

How to Get the Base URL in an MVC Controller. Here's a simple one-liner to get the job done. var baseUrl = string. Format(“{0}://{1}{2}”, Request.

Where will be the view for response is decided for a specific user request in MVC pattern?

When ASP.NET MVC attempts to resolve a view template, it will first check within the \Views[Controller] specific directory, and if it can't find the view template there it will look within the \Views\Shared directory.


1 Answers

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");
    }
like image 142
wassertim Avatar answered Oct 01 '22 01:10

wassertim