WebApi Routing issues

Damir Dobric Posts

Next talks:

 

    

Follow me on Twitter: #ddobric



 

 

Archives

One of most often my personal issue when working with WebApi is routing. Sometimes I cannot explain myself how often one can repeat same mistake. This is something what is in SOAP based protocols also an issue. If you ever worked on extending of WCF channels you will know what I mean here.

So, here is the issue. You have done everything write (you think), but you get always 404 (method not found).

HTTP/1.1 404 Not Found
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?******=?=
X-Powered-By: ASP.NET
Date: Sat, 22 Nov 2014 15:02:49 GMT
Content-Length: 246

{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:17742/api/contact/query/3'.","MessageDetail":"No

The method looks like:

       [HttpGet]
        public IEnumerable<Contact> Query(string filter)
        {
            return m_ContactDb;
        }

.. and routing looks like: this:

    
config.Routes.MapHttpRoute(

           name: "DefaultApi2",

           routeTemplate: "api/contact/query/{filter}"

       );

The problem here is that routing
was copy pasted from default route. To fix the problem we need to set the controller and action, so the WebApi can route the right request to the right action:

config.Routes.MapHttpRoute(

           name: "DefaultApi2",

           routeTemplate: "api/contact/query/{filter}"

                      defaults: new { Controller = "Contact", Action="Query" }

          );,



Posted Nov 25 2014, 08:31 AM by Damir Dobric
developers.de is a .Net Community Blog powered by daenet GmbH.