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


Question

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?

1
86
9/26/2008 3:08:27 PM

Accepted Answer

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;
107
9/26/2008 3:16:29 PM

If you need to return a reason body then have a look at WebFaultException

For example

throw new WebFaultException<string>("Bar wasn't Foo'd", HttpStatusCode.BadRequest );

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon