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?
The WebFaultException class defines a constructor that allows you to specify an HTTP status code. This status code is then returned to the client. A generic version of the WebFaultException class, WebFaultException<T> enables you to return a user-defined type that contains information about the error that occurred.
Just use Chrome browser. Hit F12 to get developer tools and look at the network tab. Shows you all status codes, whether page was from cache etc.
The origin server MUST create the resource before returning the 201 status code. If the action cannot be carried out immediately, the server SHOULD respond with 202 (Accepted) response instead.
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;
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With