How can I return a custom HTTP status code from a WCF REST method?
Solution 1
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;
Solution 2
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 );
Solution 3
For 404 there is a built in method on the WebOperationContext.Current.OutgoingResponse called SetStatusAsNotFound(string message) that will set the status code to 404 and a status description with one call.
Note there is also, SetStatusAsCreated(Uri location) that will set the status code to 201 and location header with one call.
Solution 4
You can also return a statuscode and reason body with WebOperationContext's StatusCode and StatusDescription:
WebOperationContext context = WebOperationContext.Current;
context.OutgoingResponse.StatusCode = HttpStatusCode.OK;
context.OutgoingResponse.StatusDescription = "Your Message";
Solution 5
If you wish to see the status description in the header, REST method should make sure to return null from the Catch() section as below:
catch (ArgumentException ex)
{
WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError;
WebOperationContext.Current.OutgoingResponse.StatusDescription = ex.Message;
return null;
}
Comments
-
kgriffs almost 2 years
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?