I have written several WCF data services and find them quite useful. However, I have found routing to be quite a pain. I have seen conversations that indicate that you can host a data service in an ASP.Net MVC app (I have always used ASP.Net web sites). However, I do not seem to be able to find any examples of how to achieve this. Does anybody have any references I could check-out or advice?
2 Answers
The question was posted some time ago but I assume there are still people interested in using WCF Data Services in ASP.NET MVC projects.
Assuming that you have in your project a service called: 'DataSourceService.svc' you can use this service in an MVC project by configuring the routing in 'RouteConfig.cs' as follows:
using System.Data.Services;
using System.ServiceModel.Activation;
using System.Web.Mvc;
using System.Web.Routing;
namespace <YourNamespace>
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
// the controller should NOT contain "DataSourceService"
constraints: new { controller = "^((?!(DataSourceService)).)*$" }
);
routes.Add(new ServiceRoute("DataSourceService", new DataServiceHostFactory(), typeof(DataSourceService)));
}
}
}
Make sure that you have in Web.config the following configuration:
<configuration>
...
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>
...
</configuration>
Now you can check that everything works fine by running your project in the browser and using the following url:
http://localhost:port_number/DataSourceService/$metadata
... which should return your metadata.
Comments
The WCF web api may do what you're looking for. Here's their getting started page. You host the service inside of the MVC app, and even hook into into the same routing that MVC uses.