How to return HTTP 204 response on successful DELE

2019-07-24 18:21发布

问题:

I'm having problems returning a HTTP 204 with no body using ServiceStack

If I return:

return new HttpResult() {
    StatusCode = HttpStatusCode.NoContent 
};

The first time it works perfectly, but a repeated call will cause Fiddler to throw an error stating last response wasn't formed properly. I believe it is because the content type is not explicitly set to application/json, and the response comes back with an empty string or single space character.

Setting ContentType = "json" on the HttpResult object for some reason returns a HTTP 405 response. (which is a side curiosity - not my primary concern)

If I return void, then the response is an HTTP 200, which I am using currently, but I'd like to think I could provide the preferred 204 response.

Thanks for your time.

回答1:

I use a simple response filter to set a No Content header on the response if there is no response.

Set the filter in the AppHost Configure method:

GlobalResponseFilters.Add((req, res, obj) => {
    // Handle void responses
    if(obj == null && res.StatusCode == 200)
    {
        res.StatusCode = (int)HttpStatusCode.NoContent;
        res.StatusDescription = "No Content";
    }
});

Then when a method returns void the correct header will be set.

public void Delete(TestRequest request)
{
    // I don't return anything
}

Regarding your 405 error response for JSON. This will only occur if you send an empty response and a status 200, as this is malformed JSON. But sending the above 204 No Content will prevent this error. See this answer for more info.



回答2:

I usually do something along these lines

public void Delete(FooRequest request) {
    // Perform deletion

    base.Response.StatusCode = (int)HttpStatusCode.NoContent;
}

I like this approach instead of the global response filter since this allows me to have all logic pertaining to this request in the same place instead of having to remember what response filters I have.