Question

I am using WCF to create a ReSTful service. Say my OperationContract is like this:

[OperationContract]
[WebGet(
 ResponseFormat = WebMessageFormat.Json,
 BodyStyle = WebMessageBodyStyle.Wrapped,
 UriTemplate = "GetItemList/{token}/{value}"
)]
Stream GetItemList(string token);

So when I call http://example.com/Service1.svc/GetItemList/myToken/myValue the service will be called.

Now I want to write a default method saying something link, 'No Method/End point exists', wen the user calls http://example.com/Service1.svc/GetItemList/myToken/ or http://example.com/Service1.svc/GetItemList/myValue/ or http://example.com/Service1.svc/GetItemList/

How can I implement that in my code?

Right now what I'm doing is like:

 [OperationContract]
 [WebGet(
   ResponseFormat = WebMessageFormat.Json,
   BodyStyle = WebMessageBodyStyle.Wrapped,
   UriTemplate = "GetItemList/"
 )]
 string ValidateItemList();

 [OperationContract]
 [WebGet(
   ResponseFormat = WebMessageFormat.Json,
   BodyStyle = WebMessageBodyStyle.Wrapped,
   UriTemplate = "GetItemList/{Val1}"
 )]
 string ValidateItemList(string Val1);

And in the function, I just return a string saying "No method Exists".

Is there a better way? Can I customize error messages, for urls that are directed to my service? Say, a common message for all non existing url requests, that are directed to my service?

Was it helpful?

Solution 2

I didn't find any feasible solution for my above problem. But I have found an alternate option. With VS 2012, Microsoft has released ASP.NET Web API. Which, they say, is the next version of WCF Rest. So in thet, you could handle these situations very easily. We can use the routing method in it.

Anyone intrested for that solution, can look into this post for a head start: http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

OTHER TIPS

Basically, the architecture of WCF attempts to abstract the low level components of any protocol (in this case http) away so you don't have to worry about these types of details. Unfortunate;y, that engine does not expose a nice way to handle the request's that the engine cannot route correctly.

In this case, the URI cannot be "dispatched" to the correct contract implementing class. the engine has these wonderful components called, wait for it, Dispatchers, which can be customized within the wcf framework, either by configuration or programmatically. The problem is that they are a serious pain to implement. I have implemented the unexpected message dispatcher in my answer to another question, listed below:

Handling Invalid URI passed to a WCF service

Let me know if you need any further information!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top