Tags: , , | Categories: Code Snippets Posted by Vitaly Zayko on 4/27/2011 7:47 PM | Comments (0)

When you gonna run an WCF REST service within an MVC project, you may noticed that you need to add this service to MVC routing table in Global.asax.cs file. By default it is suggested to be like this:

 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
 routes.Add(new ServiceRoute("MyRest", new WebServiceHostFactory(), typeof(MyRest)));
 
 routes.MapRoute(
     "Default", // Route name
     "{controller}/{action}/{id}", // URL with parameters
     new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
 );
 

But in this case each of your ordinary MVC Action Url will be replaced to this: /MyRest?action=Index&controller=Home which won’t work. If you put REST route to the bottom of RegisterRoutes procedure, your service will become unavailable and you’ll get 404 “Not Found” when you try to call it. Sounds like order does matter.

So the only way is to map all your routes together at the same time. Here is how your RegisterRoutes should look like:

 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
 routes.MapRoute(
     "Default", // Route name
     "{controller}/{action}/{id}", // URL with parameters
     new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
     new { controller = "^(?!MyRest).*" }
 );
 
 routes.Add(new ServiceRoute("MyRest", new WebServiceHostFactory(), typeof(MyRest)));
 

Quite tricky and not obvious at least to me. Have fun coding!

Technorati Tags: ,

Comments are closed