我想实现正确的HTTP语义,并根据资源是否已创建或更新,以及在响应内容中描述创建的资源,从我的PUT操作返回200 OK或201 CREATED。
可悲的是,PUT的Web API示例没有向您展示如何执行此操作。您应该怎么做才能指定错误代码并返回响应正文?
答案 0 :(得分:2)
如果您真的可以返回请求内容,那么这是一种更有效的方法。这将避免内容的所有反序列化和重新序列化。
public HttpResponseMessage Put(HttpRequestMessage request)
{
// do stuff
return new HttpResponseMessage(created ? HttpStatusCode.Created : HttpStatusCode.OK ) {
Content = request.Content
};
}
答案 1 :(得分: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);
}