使用json内容类型关闭streamwriter时出错

时间:2012-06-07 09:19:53

标签: asp.net json rest streamwriter

在将json内容写入流编写器后,我在关闭streamwriter时遇到错误。 以下是我正在使用的代码。找不到有什么问题。它正在写入REST服务。

WebRequest request = WebRequest.Create(String.Format("{0}/EventLog", restPath));
            request.ContentType = "application/json";
            request.Method = "POST";
            request.ContentLength = jsonstring.Length;                
            System.IO.StreamWriter sw = new System.IO.StreamWriter(request.GetRequestStream());
            sw.Write(jsonstring);                
            sw.Close();
            sw.Dispose();
            HttpWebResponse res = (HttpWebResponse)request.GetResponse();

异常:“在写入所有字节之前无法关闭流。”

1 个答案:

答案 0 :(得分:1)

确保request.ContentLength 确实等于内容长度(以字节为单位)。

这会引发同样的错误:

string data = "mydata";

WebRequest request = WebRequest.Create("http://google.de/");
request.ContentType = "application/json";
request.Method = "POST";
request.ContentLength = data.Length + 1;
System.IO.StreamWriter sw = new System.IO.StreamWriter(request.GetRequestStream());
sw.Write(data);
sw.Close();
sw.Dispose();
HttpWebResponse res = (HttpWebResponse)request.GetResponse();