Web API Attribute Routing

by clayshannon

HTML

<h2>Where's My Serrated Knife?</h2>
<p>At the risk of seeming strident or going on out on a limburger, I hereby assert that Attribute Routing (caps deliberate) is the best thing since sliced bagels.</p>

<p>The ASP.NET Web API REST extravaganza (and its brethren) use, where possible, convention over configuration. That is to say, you can name a method in your Controller Get (something), such as GetAJob() or GetReal(), and http GET methods will invoke it. </p>

<p>If you have multiple Get methods, as long as they have unique signature, all is well.</p>

<p>But what if you have two parameterless Get methods, such as one to get the count of items (returning an int) and another to get all the items (returning a collection of a particular type).</p>

<h2>Cue the Bugles (not the Bagels, the Bugles)!</h2>
<p>Never fear - Attribute Routing is here!</p>

<p>Here's an example of two Controller "GET" methods that have no arguments:</p>

<pre lang="cs">
        public int GetCountOfDuckbilledPlatypiRecords()
        {
            return _DuckbilledPlatypusRepository.GetCount();
        }

        public IEnumerable<DuckbilledPlatypus> GetAllDuckbilledPlatypi()
        {
            return _DuckbilledPlatypusRepository.GetAll();
        }
</pre>

<p>If I run the Web API app and enter in the browser: "http://localhost:28642/api/DuckbilledPlatypi" I confuse the Charles Dickens out of the router, which can only say, "Multiple actions were found that match the request: Int32 GetCountOfDepartmentRecords() on type HandheldServer.Controllers.DuckbilledPlatypiController System.Collections.Generic.IEnumerable`1[HandheldServer.Models.DuckbilledPlatypus] GetAllDuckbilledPlatypi() on type HandheldServer.Controllers.DuckbilledPlatypiController"</p>

<p>But if I add Attribute Routing, like so:</p>

<pre lang="cs">
        [Route("api/DuckbilledPlatypi/Count")]
        public int GetCountOfDepartmentRecords()
        {
            return _DuckbilledPlatypusRepository.GetCount();
        }

...