Zayko in the Net

Personal blog of Vitaly Zayko

NAVIGATION - SEARCH

About using WCF RESTful services together with ASP.NET MVC projects

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: ,

Getting the Url to virtual root in ASP.NET (C#)

Use this snippet when you need to get an Url to virtual root path in your ASP.NET projects. You may need this, for example, when you want to call dynamically a REST Web service which is part of the same project (my story). I have found few ways to do this including storing such kind of info in Web.config file. But below is more short and convenient way. Just don’t forget to add trailing slash to the end because this function doesn’t do it by its self.

 string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);

Hope this helps.

Technorati Tags: