Freigeben über


How to handle the trailing slash in a WCF HTTP Service

The other day I got this tweet from Adam

@ronljacobs anyway to do something like: [WebGet(UriTemplate = "{id}", IgnoreTrailingSlash = true)] want {id} and {id}/  to be the same

Off hand I didn’t know the answer but now that I’m back from Tech-Ed I decided to take a look at the problem.

I went to my WCF WebHttp REST Entity Service sample and because I had loads of unit tests I just created a new test case.  I had to modify my HttpTestHelper class to allow for a trailing slash.

 public void GET_MUST_return_a_resource_given_a_key_if_the_resource_with_that_key_exists_slash(WebContentFormat format)
 {
     // Arrange
     int expectedKey = 1;
  
     var testHelper = new HttpTestHelper<int, Resource>(ServiceUri);
  
     // Act
     var result = testHelper.GetResource(expectedKey, format: format, trailingSlash: true);
  
     // Assert
     Assert.AreEqual(expectedKey, result.Resource.Key);
     Assert.AreEqual(HttpStatusCode.OK, result.Status);
 }

Then I called this test case for both XML and Json formats.  As expected I now had two tests that were failing.

Why did the test fail?

Because to WCF https://localhost/resource/1 is not the same thing as https://localhost/resource/1/

But in this case, Adam wanted them to behave the same way.

Fixing the Service

Now that I had test cases that were failing, fixing them was a snap.  All I had to do was add another method to the service with the URI template the contained the trailing slash.  Then I simply call the overload that I use for requests without the trailing slash.

 // Handles the case where there is a trailing slash
 [Description("Demonstrates how to GET a resource with a trailing slash")]
 [WebGet(UriTemplate = "/{key}/")]
 public Resource GetResourceSlash(string key)
 {
     return GetResource(key);
 }

Booyah! it totally works.

WCF WebHttp REST Entity Service Sample code updated

Happy Coding!

Ron Jacobs

https://blogs.msdn.com/rjacobs

Twitter: @ronljacobs https://twitter.com/ronljacobs