How can I return a custom HTTP status code from a WCF REST method?

kgriffs picture kgriffs · Sep 26, 2008 · Viewed 67.3k times · Source

If something goes wrong in a WCF REST call, such as the requested resource is not found, how can I play with the HTTP response code (setting it to something like HTTP 404, for example) in my OperationContract method?

Answer

Eric Schoonover picture Eric Schoonover · Sep 26, 2008

There is a WebOperationContext that you can access and it has a OutgoingResponse property of type OutgoingWebResponseContext which has a StatusCode property that can be set.

WebOperationContext ctx = WebOperationContext.Current;
ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;