Archive for WCF

Using WCF for REST, Part 3

The easiest way to explain the issues we encountered when implementing REST is to work through the design principles we followed. I think much of our trouble came from the fact that we come from a web applications background, not a SOAP services background. I’m hoping that by laying out our REST design, some of the Microsoft gurus can help us do things “the WCF way.” And perhaps we can help the WCF team out by highlighting a handful of places where we found WCF unintuitive.

The Importance of Being Addressable

Fundamentally, the REST pattern is about making resources available. This means that each item stored within your system can be accessed by someone with the correct permissions. Every one of these items has its own unique address, and its address should not change. This consistency is important, because it allows both people and computer programs to remember and reference items in your system.

Note that we’re talking about resources or items. In contrast with the SOAP model of web services, which allows programmers to invoke procedures on remote computers, REST is about providing data. SOAP is about verbs, while REST is about nouns. A SOAP service might CalculateTotalSale(); a REST service provides CustomerRecieptNo_12345. The kind of web services architecture you use will depend on the kind of application you’re building. The choice has major implications for the other components of your system.

REST imposes restrictions on what sort of things you can do, because it supports only a handful of actions: GET, POST, PUT, and DELETE. (There are a few other HTTP methods, but these four are the most important.) Fortunately, with these four actions, you can accomplish most basic programming tasks. There’s a close parallel to these actions and create/read/update/delete, or CRUD, the building blocks of data storage systems.

UriTemplate

Since the address, or URI, is the primary way to access information in your system, it’s effectively part of your user interface. All the principles of good user interface design apply. So when designing a REST service, you need fine control over the structure of these identifiers.

SOAP, by contrast, typically has just one endpoint. The address itself conveys no information about what services are provided — that’s why SOAP services require a separate WSDL file to tell folks what’s possible. With REST, it should be easy to discover the extent of the system by looking at the URIs alone.

Coming up with good REST URI patterns can be tricky. Using short, descriptive naming conventions for your resources makes them easier to type. But URI patterns must also be distinct and unambiguous.

In the .NET framework, you use the UriTemplate class to define patterns. The UriTemplate implementation that shipped with .NET 3.5 allowed you to define variables that fit into slots in your URI. A typical UriTemplate might look like this: http://restserver/{object}/{id}?view={viewname}.

WCF looks for incoming URIs that match the patterns you define. The pattern defined above would match the following URIs:

  • http://restserver/customer/5?view=profile
  • http://restserver/article/how_to_do_stuff?view=print
  • http://restserver/author/John-Smith?view=1

Once you’ve defined a UriTemplate, you bind it to a method that has the same number of parameters. (I won’t go into the ABCs of WCF here, but you can check out this MSDN Introduction to WCF if you need a refresher.)

In WCF 3.5, you could only define a variable for a whole segment. A segment is basically the bit between the one forward slash and another, or one querystring parameter. A few bloggers requested more flexibility in UriTemplates, and the WCF team answered with the soon-to-be-released 3.5 SP1. The ability to define variables for partial segments was crucial for our URI design.

Representation Matters

Most books about web services, including RESTful Web Services, advocate leaving off file extensions from your URIs. This makes sense for SOAP, where you’re accessing methods and all responses are transmitted in XML. But in REST, you’re serving up items.

In our case, some of these items being served were files and some were records from a database. It seemed inconsistent to have some endpoints that had file extensions and others that didn’t. And we also wanted to be able to serve up different representations for our database records. Our REST service supports both JSON, XML, and HTML. It made sense to use a file extension to distinguish between the different representations.

One workaround would have been to create endpoints like http://restserver/form/1040/xml but that looked funny next to URIs like http://resterver/file/documentation.pdf. True RESTafarians would point out that neither the “/xml” or the “.pdf” are needed, since you can request an appropriate representation using the HTTP ACCEPT header. We decided against the header approach because not all browsers use the ACCEPT HTTP header. Besides, it might be useful for us humans to be able to reach alternate formats by simply changing the URL in the browser address bar.

In WCF 3.5, this required us to create three times the number of endpoints, with a separate method to handle each. We can’t wait for the official release of 3.5 SP1 to make UriTemplates like http://restserver/user/{id}.{ext} possible.

The Final Slash

Another source of endpoint duplication was the need to have two different endpoints for http://restserver/folder and http://restserver/folder/. Because the slash is used as a segment delimiter, the dispatcher in WCF 3.5 saw these two URLs as fundamentally different.

So handling what we thought were fairly trivial cases in URI patterns led us to create FIVE TIMES the number of endpoints we wanted. It’s a maintenance nightmare. SP1 can’t get here soon enough.

WCF Instance Context

I finally figured out the source of my HTTP 400 problem. Apparently the Windows Communication Foundation deals with exceptions differently depending on your InstanceContextMode settings. I had been using the Single setting but I should have used the PerCall setting. In PerCall mode, the try/catch block works as expected.

I think it has something to do with the way that WCF distinguishes between channel exceptions and message faults.

Anyway, if you’re building a REST web service, you’ll want to make sure your class is decorated with the following ServiceBehavior attribute.

  1. [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]

Using WCF for REST, Part 2

In part one of this series, I listed several websites and blogs that had useful information on the Windows Communication Foundation (WCF) and REST. I also mentioned that if I was stating again, I’d probably use something other than WCF. Perhaps deriving my own REST server from System.Net.HTTPListener, for example.

Vish asked for some additional details in his comment to that post. He works on the Microsoft WCF development team and was curious about our experience.

I had just begun putting together my response when I noticed Scott Guthrie’s post about Service Pack 1 for the .NET Framework 3.5 beta release. Steve Maine also posted specifics about the ADO.Net Data Services and WCF changes.

So, Vish, it seems your team’s beaten me to the punch on some of these issues! Many of the difficulties I was having with WCF and REST were addressed by the service pack. Here’s an overview of our key stumbling blocks:

  1. REST requires much greater control over the URI than SOAP does, and the URITemplate class just wasn’t up to the task. We had to hardcode most of our endpoints to compensate. (Fixed in SP1. Hooray!)
  2. Supporting multiple formats, such as serving both XML and JSON, either require you to program against Stream or require twice the number of endpoints.
  3. Existing serializers had trouble with complicated object graphs, forcing us to perform serialization/deserialization ourselves. (This seems greatly improved in SP1.)
  4. WCF allows only one contract/interface per endpoint. This makes it tricky to factor out common contract patterns.
  5. Good REST practice would have you return many kinds of errors as HTTP status messages. SOAP embeds all error information in the returned XML. WCF is closely aligned with the SOAP approach, which means that you’ve got to be very careful distinguishing exceptions from faults when implementing REST in WCF. It was an unpleasant surprise, and we had to do quite a bit of work to deal with that.

I’ll talk about all five of these areas in more detail in upcoming posts in this series. And I’ll be sure check out the SP1 beta once we get our Infovark Alpha release out the door.

Using WCF for REST, Part 1

Just because you can do something doesn’t mean it’s a good idea.

We decided to use the Windows Communication Foundation to drive our REST-based web service. In hindsight, it was a poor choice. REST support in WCF seems like it was a last-minute addition to .NET 3.5. You can certainly hack something together, but I’ve found few real-world examples on the Internet, and most of those sidestep the tricky issues.

Here’s the short of it: WCF was designed for RPC-SOAP. More importantly, it was designed to SOA-enable legacy services that used older communications channels like DCOM. If you’re starting from scratch, and have full control over the output of your web service and the design of your object model, I’d recommend using a different (and simpler) framework.

We’ve gotten a good bit of blog traffic from people looking for help with Windows Communication Foundation and the REST architectural pattern. (It’s good to know that we’re not the only ones needing advice.) Here are the better sources we’ve found so far.

Windows Communication Foundation documentation on MSDN

Good overview presentation on REST and Syndication using WCF

Microsoft’s Picture Services Sample

Justin Smith’s WCF articles on Cybertopian Chronicles

Nicholas Allen’s Indigo blog

Steve Maine’s blog

Assorted posts on Rick Strahl’s blog

That Indigo Girl

If you find other useful places to look, let us know!

WCF Bad Request

I’ve just identified a horrible bug in WCF for the .NET Framework 3.5.

A caught exception in a WebInvoke operation will cause WCF to return an HTTP 400 Bad Request status code to the client. Any caught exception. Every time. Regardless of whatever error code you might want to send back.

I found the error by mistake. I’d used “BadGateway” instead of “BadRequest” in my code. If it weren’t for other odd WCF behavior, I wouldn’t have noticed that my status code was being ignored.

Consider the following example:

  1.  // Read the Xml into our object and save.
  2.  try
  3.  {
  4.   // The following line triggered the error.
  5.   obj.ReadXml(reader);
  6.   obj.Save();
  7.   // Set HTTP Cache Options and MIME Type.
  8.   Utilities.SetCaching(WebOperationContext.Current, obj.DateModified, 60);
  9.   Utilities.SetMimeType(Format.Xml);
  10.   return Utilities.GetXmlStream(obj);
  11.  }
  12.  catch (Exception e)
  13.  {
  14.   // Was it a schema validation error? If so, provide detail.
  15.   if (!string.IsNullOrEmpty(_XmlValidationErrors))
  16.   {
  17.    // I slipped here, using BadGateway 502 instead of Bad Request 400.
  18.    // But WCF doesn't care. If you enter the catch block it's _always_ 400.
  19.    WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.BadGateway;
  20.    WebOperationContext.Current.OutgoingResponse.StatusDescription = _XmlValidationErrors;
  21.    WebOperationContext.Current.OutgoingResponse.SuppressEntityBody = false;
  22.    return null;
  23.   }
  24.  }

If no error occurs, WCF will return the status code you specify. A try/finally block will work just fine; WCF returns whatever status code you specify. Enter a catch block, though, and it’s nothing but 400 Bad Request.

Hey, if there’s an error, it must be the client’s fault, right?

WCF, WebHttp Binding, and Authentication

If you’re trying to build REST-enabled services with WCF, you’ll want to use the webHTTP Binding.

This binding defaults to anonymous handling, so if you’re planning on doing any authorization you need to change the binding configuration.

This took me ages to figure out, largely because the webHttp binding is new and not well documented.

To change the binding to support NTLM or Windows authentication, add the following node to the system.servicemodel in your app.config:

  1. <bindings>
  2. <webHttpBinding>
  3. <binding name="varkBinding">
  4. <security mode="TransportCredentialOnly">
  5. <transport clientCredentialType="Ntlm"  />
  6. </security>
  7. </binding>
  8. </webHttpBinding>
  9. </bindings>

Note that you can supply one of five values to the mode attribute: None, Basic, Digest Windows, NTLM, and Certificate.

Once you’ve picked the one you want, in your service definition, specify your new binding from the bindingConfiguration attribute:

  1. <service behaviorConfiguration="SyndicationBehavior"
  2. name="Yourapp.Yourservice">
  3. <endpoint address="http://localhost:8000/url"
  4. behaviorConfiguration="SomeBehavior"
  5. binding="webHttpBinding" bindingConfiguration="varkBinding"
  6. contract="YourContract.IYourService" />
  7. </service>

And all calls to your REST service should be made with a valid windows network identity.

In your serviceCode, you can retrieve it from the System.ServiceModel namespace:

  1. ServiceSecurityContext.Current.WindowsIdentity

Oh, and if you’re not comfortable with editing the XML files, or you’d like to explore the dizzying array of other available options in WCF, I also discovered the Microsoft Service Configuration Editor (possibly someone had discovered it before me. ) It lives at C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\SvcConfigEditor.exe. It gives you a simple(ish) visual way to edit WCF Configuration files.

UPDATE: JustinJSmith over at The Cybertopian Chronicle points out that it’s even easier to invoke the config editor - you just right click on your app.config, and select “Edit WCF Configuration” (duh…)