【问题标题】:Error while closing streamwriter with json content type使用 json 内容类型关闭 streamwriter 时出错
【发布时间】:2012-06-07 09:19:52
【问题描述】:

我在将 json 内容写入流写入器后关闭流写入器时出错。 以下是我正在使用的代码。找不到什么问题。它正在写入 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();

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

【问题讨论】:

  • 试试 sw.Flush();关闭前
  • 已经试过 sw.Flush();,不行。
  • sw.BaseStream.CanWrite? 是怎么回事
  • sw.BaseStream.CanWrite 的值在运行时为真,并且 close 方法给出相同的错误。

标签: asp.net json rest streamwriter


【解决方案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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    • 2020-08-05
    • 2023-03-21
    • 2018-03-05
    • 2015-12-15
    • 2019-05-15
    相关资源
    最近更新 更多