/ DOTNET, MVC, ROUTING

Update and Routing

A lot has happened in the month since I last wrote.

I was very busy with my practicum and neglected some of my own projects. I then went on vacation to Maui for one week, and started watching the Covid-19 crisis unfold from afar. Currently I am at home in self-isolation, working remotely to finish my practicum. I have great luck and timing - 14 day self-isolation, with 2 weeks left of my practicum. After that, I’m not sure what my situation will be. Perhaps it will be an opportunity to continue my dev learning full time. Let’s go with that.

I’m going to try writing posts with one topic only, for now. This post will explain what I know about routing in .NET.

One definition I will use: Overload: in C#, some methods will have the same name but can accept different parameters(aka arguements, in other languages). These different options are called “overloads”. You overload one method, rather than writing multiple methods that do the same thing but use different parameters.

You deal with routing in your RouteConfig.cs file. To create custom routes you have 2 main approaches: Convention-based and Attribute routing. Attribute routing is cleaner and is the recommended way.

Convention-based:

  • in RegisterRoutes, put routes in order of most specific to most generic
  • create routes.MapRoute(); before default route
  • the most commonly used overload accepts 3 parameters: name, url, and default
  • default defines the controller and action that you will use
  • once you create this, you go to the corresponding controller and create the action result
  • MapRoute() can accept another argument for constraints (like number of digits in a year or month) - can define using regular expressions

For large applications, you can accumulate many custom routes in your RouteConfig.cs file, so you can use attribute routing to make it cleaner.

Attribute routing:

  • use attribute above action in controller, rather than creating it in RouteConfig.cs
  • in RouteConfig.cs, add routes.MapMvcAttributeRoutes();
  • for example, in controller type the following above your action [Route(“movies/release/{year}/{month:regex(\d{2}”)})]
  • constraints placed directly in attribute