如何使用 ServiceStack 在成功删除时返回 HTTP 204 响应 [英] How to return HTTP 204 response on successful DELETE with ServiceStack
问题描述
我在使用 ServiceStack 返回没有正文的 HTTP 204 时遇到问题
I'm having problems returning a HTTP 204 with no body using ServiceStack
如果我回来:
return new HttpResult() {
StatusCode = HttpStatusCode.NoContent
};
第一次运行完美,但重复调用会导致 Fiddler 抛出一个错误,指出最后一个响应的格式不正确.我相信这是因为内容类型没有明确设置为 application/json
,并且响应返回一个空字符串或单个空格字符.
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.
由于某种原因在 HttpResult
对象上设置 ContentType = "json"
会返回 HTTP 405 响应.(这是一个附带的好奇心 - 不是我的主要关注点)
Setting ContentType = "json"
on the HttpResult
object for some reason returns a HTTP 405 response. (which is a side curiosity - not my primary concern)
如果我返回 void,则响应是 HTTP 200,我目前正在使用它,但我想我可以提供首选的 204 响应.
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.
感谢您的时间.
推荐答案
如果没有响应,我使用一个简单的响应过滤器在响应上设置一个 No Content
标头.
I use a simple response filter to set a No Content
header on the response if there is no response.
在AppHost
Configure
方法中设置过滤器:
GlobalResponseFilters.Add((req, res, obj) => {
// Handle void responses
if(obj == null && res.StatusCode == 200)
{
res.StatusCode = (int)HttpStatusCode.NoContent;
res.StatusDescription = "No Content";
}
});
然后当方法返回 void
时,将设置正确的标头.
Then when a method returns void
the correct header will be set.
public void Delete(TestRequest request)
{
// I don't return anything
}
关于 JSON 的 405
错误响应.仅当您发送空响应和状态 200
时才会发生这种情况,因为这是格式错误的 JSON.但是发送上面的 204 No Content
可以防止这个错误.有关详细信息,请参阅此答案.
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.
这篇关于如何使用 ServiceStack 在成功删除时返回 HTTP 204 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!