Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rest

c#

.net

wcf

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?

like image 558
kgriffs Avatar asked Sep 26 '08 15:09

kgriffs


People also ask

How can I get my HTTP status code in WCF service?

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.

How can I get HTTP status code?

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.

Which HTTP status code is usually returned when a resource was found and returned?

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.


2 Answers

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; 
like image 75
Eric Schoonover Avatar answered Oct 13 '22 05:10

Eric Schoonover


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 ); 
like image 26
Graeme Bradbury Avatar answered Oct 13 '22 04:10

Graeme Bradbury