发送连续的帖子

时间:2016-03-24 17:35:08

标签: c# asp.net exception parallel.foreach aggregateexception

我想将POST()数据顺序发送到网站。我希望post1完成,然后开始post2,然后开始post3等等。我有编译的语法,但是我得到一个错误,我不确定如何克服。

  

发现了AggregateException   发生一个或多个错误

这是我使用的语法:

private multipost()
{
  string postsite = string.Format("http://requestb.in/1g5y7234");
  string postData = "";
  string responseMessage = "";

  DataTable grds = new DataTable();
  grds.Columns.Add("Dosage", typeof(int));
  grds.Columns.Add("Drug", typeof(string));
  grds.Columns.Add("Patient", typeof(string));
  grds.Columns.Add("Date", typeof(DateTime));
  grds.Rows.Add(25, "Indocin", "David", DateTime.Now);
  grds.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
  grds.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
  grds.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
  grds.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);

  try
  {
    Parallel.ForEach(grds.Rows.OfType<DataRow>(), row =>
    {
        foreach (var item in row.ItemArray)
        {
            postData += "=" + item + "&";
            postData += "d2p=";
            System.Net.HttpWebRequest r = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(postsite);
            r.Method = "POST";
            r.Accept = "application/json";
            r.ContentType = "application/x-www-form-urlencoded";
            r.ContentLength = postData.Length;
            r.KeepAlive = false;
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter(r.GetRequestStream()))
            {
                try { sw.Write(postData); }
                catch (Exception ex) { responseMessage = ex.Message; }
            }
            var response = r.GetResponse();
            Stream receiveStream = response.GetResponseStream();
            StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
            var result = readStream.ReadToEnd();
            var xml = System.Xml.Linq.XElement.Parse(result);
            if (xml.Elements("success").FirstOrDefault().Value == "1") { responseMessage = "Success"; }
            else
            {
                var errors = xml.Elements("errors");
                foreach (var error in errors.Elements("error")) { responseMessage = error.Value; }
            }
        }
    });
  }
  catch (Exception mbop) { throw mbop; }      
}

看起来我忘了向强大的头脑提出一个问题。导致此错误的原因是,我该如何克服此错误?

修改
我将catch{}块改为

catch (Exception mbop) 
{
    while (mbop.InnerException != null)
        throw mbop;
} 

它产生的InnerException

  

根级别的数据无效。第1行,第1位

0 个答案:

没有答案