Request.CreateErrorResponse导致ProtocolViolationException - 内容长度不正确

时间:2014-06-30 11:46:15

标签: c# asp.net-web-api

我试图从Web API中的控制器get方法设置一个相当直接的NotModified状态。我使用Request.CreateErrorResponse扩展方法来简化流程,但是一旦返回响应,我就会抛出ProtocolViolationException:

response = Request.CreateErrorResponse(System.Net.HttpStatusCode.NotModified, "File up to date.");

我现在只是创建一个空响应并设置StatusCode来解决这个问题:

response = Request.CreateResponse();
response.StatusCode = System.Net.HttpStatusCode.NotModified;

HttpConfiguration设置为启用XmlSerializer,并删除JSON格式化程序。

一个解释可能是扩展方法代码背后的某个错误,但我无法想知道是否还有其他我在这里丢失的东西。有没有人遇到过这个问题,或者对于如何触发这个问题有任何解释?我还包括了堆栈跟踪以供参考:

2014-07-01 02:41:16,505 [ERROR] [End][XmlMediaTypeFormatter.WriteToStreamAsync] 
System.Net.ProtocolViolationException: Bytes to be written to the stream exceed the Content-Length bytes size specified.
   at System.Net.HttpResponseStream.BeginWrite(Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state)
   at System.ServiceModel.Channels.HttpOutput.ListenerResponseHttpOutput.ListenerResponseOutputStream.BeginWrite(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback callback, Object state)
   at System.ServiceModel.Channels.BufferedOutputAsyncStream.ByteBuffer.FlushAsync()
   at System.ServiceModel.Channels.BufferedOutputAsyncStream.DequeueAndFlush(ByteBuffer currentBuffer, AsyncEventArgsCallback callback)
   at System.ServiceModel.Channels.BufferedOutputAsyncStream.FlushPendingBuffer()
   at System.ServiceModel.Channels.BufferedOutputAsyncStream.Flush()
   at System.Xml.XmlUtf8RawTextWriter.Flush()
   at System.Xml.XmlWellFormedWriter.Flush()
   at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
   at System.Net.Http.Formatting.XmlMediaTypeFormatter.<>c__DisplayClass7.<WriteToStreamAsync>b__6()
   at System.Threading.Tasks.TaskHelpers.RunSynchronously(Action action, CancellationToken token)

0 个答案:

没有答案