Controllers in MVC

Introduction 

 
In MVC the URLs are mapped to the Controllers action method so the question is how URLs are mapped to the Controllers action method?
 
The answer for that ASP.NET routing. It is registering in Global.asax file.
 
The Registeroute method Is present in the RouteConfig.cs file
 
Below is the RegisterRoute method in that class file. 
  1. public static void RegisterRoutes(RouteCollection routes)  
  2. {  
  3.    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  4.   
  5.    routes.MapRoute(  
  6.       name: "Default",  
  7.       url: "{controller}/{action}/{id}",  
  8.       defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }  
  9.       );  
  10.    }  
  11. }  
In the above code, you can see that the Default route is present. It means if you simply run the application, then it will invoke this URL path the normal path which you see after run application https://localhost:44374/.
 
This URL is the same as https://localhost:44374/Home/Index this URL is the same as the above URL. The controller is Home and action is Index.
 
So, in the RegisterRoute method MapRoute method if you see that ID is an optional parameter, but if you pass and you need to access this you need to modify the action method signature in the controller.
 
This is one way to get the QueryString parameter from URL to action, but you can also use our older way to access the parameters. Use the below method for that.
  1. public ActionResult Index(string id)  
  2. {  
  3.    ViewBag.id = id;  
  4.    ViewBag.name =Request.QueryString["name"];  
  5.    return View();  
  6. }  
Above ID code for that, in above code we use Request.QuerySting method to access URL parameters and application works as expected.
In the Register.Route method, add one more method
  1. routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
This is used to ignore the file with the extension .axd. It means that the request is not passed to the below MapRoute method and file directly get from this.