Posts tagged REST
Pretty URIs in WCF Data Services – Lose the .svc File
Apr 6th
I’m still testing this, but, it looks like in .NET 4 you will be able to use the new URL Routing to lose the .svc file in your WCF Data Services.
Step-by-step
Follow the standard steps for creating a WCF Data Service.
- Create a new, “Empty ASP.NET Web Application”
- Add an Entity Data Model
Once you have your entity data model, add a new class, derive it from DataService<T> where T is the entity set you created in the previous steps:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data.Services; using System.Data.Services.Common; namespace ODataSample { public class ProductService : DataService<AdventureWorksLT2008Entities> { public static void InitializeService(DataServiceConfiguration config) { config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; config.SetEntitySetAccessRule("Products", EntitySetRights.AllRead); config.SetEntitySetPageSize("Products", 20); } } }
Add a Global Application Class (global.asax). In the Application_Start method add the following snippet:
RouteTable.Routes.Add(new ServiceRoute("ProductCatalog", new WebServiceHostFactory(), typeof(ProductService)));
If all is well you should be able to hit F5 to debug. Since there is not a default page you’ll have to add the route name you specified onto the end of the URI. If all goes well you should see:
In my testing thus far it appears everything works as you’d expect in terms of appending on query parameters, etc.
Redirecting From a WCF REST Service
Mar 27th
REST is based on HTTP and revolves around using the standard HTTP verbs GET, POST, PUT as well as standard HTTP error codes. The error codes that have to do with redirection are in the 300 block. Today we’ll focus on 302 which is the status code for a redirection (other 300 codes, such as 301 indicate that the URI moved permanently).
The following code will redirect the client with a 302 status code:
WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.Redirect; WebOperationContext.Current.OutgoingResponse.Location = "/someOtherPage.aspx"; return null;
For an additional measure we’ll return null as well so that there is no output emitted to the client. The end result will be that the headers include the 302 status code, the location to redirect to and the body of the response will be empty.
Drop the Soap: WCF, REST, and Pretty URIs in .NET 4
Mar 17th
Years ago I was working in libraries when the Web 2.0 revolution began. One of the things that caught my attention about early start-ups using the AJAX/REST/Web 2.0 model was how nice the URIs were for their applications. Those were my first impressions of REST; pretty URIs. Turns out there is a little more to it than that.
REST is an architectural style that focuses on resources and structured ways to access those resources via the web. REST evolved as an “anti-SOAP” movement, driven by developers who did not want to deal with all the complexity SOAP introduces (which is al lot when you don’t have frameworks hiding it all). One of the biggest benefits to REST is that browsers can talk to rest services directly because REST works using URIs, QueryStrings, Cookies, SSL, and all those HTTP verbs that we don’t have to think about anymore.
If you are familiar with ASP.NET MVC then you have been exposed to rest at some level. MVC is relies heavily on routing to generate consistent and clean URIs. REST for WCF gives you the same type of feel for your services. Let’s dive in.
WCF REST in .NET 3.5 SP1 and .NET 4
This post will cover WCF REST in .NET 4 which drew heavily from the REST Starter Kit and community feedback. There is basic REST support in .NET 3.5 SP1 and you can also grab the REST Starter Kit to enable some of the features you’ll find in .NET 4.
This post will cover REST in .NET 4 and Visual Studio 2010.
Getting Started
To get started we’ll create a basic WCF Rest Service Application using the new on-line templates option in VS 2010:
When you first install a template you are prompted with this dialog:
Dude Where’s my .Svc File?
The WCF REST template shows us the new way we can simply build services. Before we talk about what’s there, let’s look at what is not there:
- The .Svc File
- An Interface Contract
- Dozens of lines of configuration that you have to change to make your service work
REST in .NET 4 is greatly simplified and leverages the Web Routing capabilities used in ASP.NET MVC and other parts of the web frameworks. With REST in .NET 4 you use a global.asax to set the route to your service using the new ServiceRoute class. From there, the WCF runtime handles dispatching service calls to the methods based on the Uri Templates.
global.asax
using System; using System.ServiceModel.Activation; using System.Web; using System.Web.Routing; namespace Blog.WcfRest.TimeService { public class Global : HttpApplication { void Application_Start(object sender, EventArgs e) { RegisterRoutes(); } private static void RegisterRoutes() { RouteTable.Routes.Add(new ServiceRoute("TimeService", new WebServiceHostFactory(), typeof(TimeService))); } } }
The web.config contains some new structures to support a configuration free deployment. Note that this is the default config generated with the template. I did not make any changes to web.config.
web.config
<?xml version="1.0"?> <configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <system.webServer> <modules runAllManagedModulesForAllRequests="true"> <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> </modules> </system.webServer> <system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/> <standardEndpoints> <webHttpEndpoint> <!-- Configure the WCF REST service base address via the global.asax.cs file and the default endpoint via the attributes on the <standardEndpoint> element below --> <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/> </webHttpEndpoint> </standardEndpoints> </system.serviceModel> </configuration>
Building the Time Service
We’ll create a simple “TimeService” that will return the current time. Let’s start with the following code:
using System; using System.ServiceModel; using System.ServiceModel.Activation; using System.ServiceModel.Web; namespace Blog.WcfRest.TimeService { [ServiceContract] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] public class TimeService { [WebGet(UriTemplate = "CurrentTime")] public string CurrentTime() { return DateTime.Now.ToString(); } } }
The endpoint for this service will be http://[machinename]:[port]/TimeService. To get the current time http://[machinename]:[port]/TimeService/CurrentTime will do the trick.
The Results Are In
Remember That Route In global.asax?
Turns out it is pretty important. When you set the route name, that defines the resource name starting after the host portion of the Uri.
Help Pages in WCF 4
Another feature that came from the starter kit are the help pages. To access the help pages simply append Help to the end of the service’s base Uri.
Dropping the Soap
Having dabbled with REST in the past and after using Soap for the last few years, the WCF 4 REST support is certainly refreshing. I’m currently working on some REST implementations in .NET 3.5 and VS 2008 and am looking forward to working on REST in .NET 4 and VS 2010.

