Tim Lovell-Smith
Tim Lovell-Smith

Reputation: 16135

Web API - How do I return a specific status code in the response?

I want to implement proper HTTP semantics and return 200 OK or 201 CREATED from my PUT action depending on whether the resource was created or updated, and also in the response content describe the created resource.

Sadly the Web API sample for PUT doesn't show you how to do this. What are you supposed to do to specify an error code AND return a response body?

Upvotes: 1

Views: 1177

Answers (2)

Darrel Miller
Darrel Miller

Reputation: 142222

If you really can just return back the request content, then here is a more efficient way. This will avoid all deserializing and reserializing of the content.

public HttpResponseMessage Put(HttpRequestMessage request)
    {
        // do stuff

        return new HttpResponseMessage(created ? HttpStatusCode.Created : HttpStatusCode.OK ) {
            Content = request.Content
        };
    }

Upvotes: 2

Tim Lovell-Smith
Tim Lovell-Smith

Reputation: 16135

    // PUT 
    // path/to/{resourceName}
    public HttpResponseMessage Put(CreateResourceRequest request)
    {
        //do stuff...

        // Return 200 [OK] if it is an update and 201 [CREATED] if the resource is created. 
        // Usually, the response body should be same as the original request.
        var responseContent = request;
        return Request.CreateResponse(created ? HttpStatusCode.Created : HttpStatusCode.OK, responseContent);
    }

Upvotes: 0

Related Questions