One of the most important changes in Asp.Net Core was mixing the WebAPI and MVC. Now they are not two separate things, Asp.Net Core now contains both of them, that means these two technologies are going to share the same code base for a lot of things, and attribute routing is one of them. In this post I’m going to discuss the changes that are made to routing system in Asp.Net Core, and look at some of its differences.
MVC 5 Routing: HttpGet Routes Mix Itself With HttpPost
One of the great feature that came with MVC 5 was attribute routing, but it was not totally without faults, for example the route values were static, or even worse the route values that was used on HttpGet version of an action, also were effecting the HttpPost version of the action, for example consider the action below:
Here we have “SelectEmail” method that responds to “HttpGet”, now let’s assume we had a method with the same name, but without any routing attribute like this:
In MVC 5 what is happen with situation like this is that, now our HttpPost method has the same route as our HttpGet method because we set the route on HttpGet, and now we have to set the route for HttpPost specifically like so:
Asp.Net Core Routing: RESTful Style Routes With Asp.Net Core Attribute Routing
Now with Asp.Net Core we no longer have the problem that I mentioned above, not only that, but now we can even declare RESTful like routes like [HttpGet(“Our Route”)] and [HttpPost(“Our Route”)].
This cause the code to be cleaner and less cluttered and we don’t have the problems that we had when we were using MVC 5.
Asp.Net Core Routing: Attribute Routing Dynamic Controller and Action Name
In the past we had to specify the controller and action name specifically, and if down the road we decide to change our controller or action name, we had to change the routes too. But now with new features added in Asp.Net Core we can declare that we want to use the same name for some section of our route as our controller or action, like this:
Asp.Net Core Routing: Define Data Type and Default Value For Route Parameter
With Asp.Net Core Routing, now we can constrain the data type of our route parameters, or provide default value for it:
I’m sure I’ve only scratched the surface of the great changes that comes with Asp.Net Core routing, but these where the most noticeable in my opinion, if you think I’ve missed something, feel free to correct me by leaving a comment, have a good day.