1

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?

2 Answers 2

2

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
        };
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Cool, that's a nice tip! :)
0
    // 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);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.