Using WCF in a RESTful way seems great. I’m a big fan of the big guns like simplicity and flexibility, but I also love the way the Urls end up looking. What can I say, I’m a
Send the proper response code and you can supply the custom error message in the body of the response.
See this thread for a similar question.
In a nutshell I believe you can set the HTTP status code (to one of the error codes), and provide your custom message in the StatusDescription property:
OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
response.StatusCode = System.Net.HttpStatusCode.Forbidden;
response.StatusDescription = "Custom";
I don't know much about the prevalence of this technique in the real world unfortunately.
With .net 4, throw a WebFaultException<T>(T errorDetail,
HttpResponseCodecode)
Here you set your response type to another object type, which makes sense, and also you set the ResponseCode
that you want.
The errorDetail
must be serializable
http://blogs.msdn.com/b/endpoint/archive/2010/01/21/error-handling-in-wcf-webhttp-services-with-webfaultexception.aspx
I add the error code both as above (in the status description) and in the body of the returned page in my REST services as:
OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
response.StatusCode = HttpStatusCode.Unauthorized;
response.StatusDescription = "You are not authorized.";
HttpContext.Current.Response.Write("You are not authorized.");
return null;
This may be a defect. As of 9/22/2011, the issue is under review by the product team:
http://connect.microsoft.com/VisualStudio/feedback/details/690162/wcf-rest-custom-outgoingwebresponsecontext-statusdescription-not-returned-in-response