I was recently working on a project whereby Attribute-based routing was being used in conjunction with Partial Classes for Web API Controllers.
While I will not going into the details of this inherent design flaw, it allowed me to better understand the problems inherent with Attribute-based routing and why so many developers prefer defining explicit routes in the WebApiConfig.cs class file.
While I will not going into the details of this inherent design flaw, it allowed me to better understand the problems inherent with Attribute-based routing and why so many developers prefer defining explicit routes in the WebApiConfig.cs class file.
- The first thing I noticed as an inherent limitation of Attribute-based routing was that you can only define the RoutePrefix attribute on a single class instance even in a partial class scenario. Therefore, if you have a partial class that splits across 2 files, this means that the RoutePrefix can only exist on one of the 2 files, thus making it more difficult to understand what is the RoutePrefix definition when switching between the 2 files. Now, just imagine, if that partial class is split across 3 or more files!
- Another thing that I noticed was Attribute-based routing does not work perfectly on all methods even when defining a RoutePrefix in a class file. I had one instance of a class that was using more than 8 parameters in the method definition, and it also had no route attribute assigned to it. In this instance, the RoutePrefix was being totally ignored by ASP.NET Web API and instead only the Default Route was being used for this particular method. Scenarios like this make Attribute-based routing even more troublesome.
- In simple instances where you are using the RoutePrefix on a class, if you forget to decorate your other methods with the Route attribute, once again these routes will not follow the Attribute-based routing convention and revert to the Default Route defined in WebApiConfig.cs.
These are just a few of the more blatant reasons that I discovered while working with Attribute-based routing. I am sure there are many more cases than these to prefer defining explicit routes in WebApiConfig.cs, but at least now you know the consequences of choosing an Attribute-based routing scheme for your ASP.NET Web API Web Applications!
No comments:
Post a Comment