情况
看起来很简单:我有一个在 IIS 7 上运行的服务。一个客户端发布数据(应用程序/json),我在接受数据之前验证数据。
如果我不接受它,我真的很想返回一个 406 和 ~same~ 数据作为正文(可能更改/更正)[1]。不幸的是,这会导致响应体被截断,也就是无效的 json。
首先,让我们为我的错误启用直通,否则 IIS 会尝试变得聪明:
<httpErrors errorMode="Detailed" existingResponse="PassThrough">
</httpErrors>
我的代码的相关部分在道德上与此等效:
HttpResponseBase response = context.HttpContext.Response;
response.StatusCode = StatusCode;
response.StatusDescription = StatusDescription;
if (!string.IsNullOrEmpty(ContentType))
response.ContentType = ContentType;
else
response.ContentType = "application/json";
if (ContentEncoding != null)
response.ContentEncoding = ContentEncoding;
using (var sw = new StreamWriter(response.OutputStream))
{
sw.Write(JsonConvert.SerializeObject(Data));
}
在客户端,我目前正在做一个幼稚的事情(找到 json 截断的问题)
var response = myRestClient.Execute(myRestRequest);
问题
如果响应返回状态码 200,我得到这个
response.ContentLength == 69345
response.RawBytes.Length == 69345
如果我只更改返回的状态码(在我的情况下为 406),返回完全相同的数据,我会看到:
response.ContentLength == 69345
response.RawBytes.Length == 65536 // <--- Not! Good!
现在,65536 这个数字太神奇了,不可能是宇宙射线的巧合或非常可重现的结果。如果我的数据长度超过无符号短,谁现在想变得聪明并丢弃我的数据?我现在将尝试深入研究 RestSharp 代码库,但我真的很怀疑 IIS 再次欺骗了我。
1:如果这是一个坏主意,请详细说明为什么?