2011-06-28 46 views
2

爲什麼要req.GetRequestStream()。Close();原因「ProtocolViolationException - 無法使用此動詞類型發送內容主體。」代碼片段從here。謝謝。ASP.NET ProtocolViolationException - 無法使用此動詞類型發送內容正文

 WebRequest req = null; 
     WebResponse rsp = null; 
     try 
     { 
      string fileName = "Login.xml"; 
      string uri = "http://localhost/api/login"; 
      req = WebRequest.Create(uri); 

      //req.Proxy = WebProxy.GetDefaultProxy(); // Enable if using proxy 
      req.Method = "POST";  // Post method 
      req.ContentType = "text/xml";  // content type 

      // Wrap the request stream with a text-based writer 
      StreamWriter writer = new StreamWriter(req.GetRequestStream()); 

      // Write the XML text into the stream 
      writer.WriteLine(this.GetTextFromXMLFile(fileName)); 
      writer.Close(); 

      // Send the data to the webserver 
      rsp = req.GetResponse(); 

     } 
     catch (WebException webEx) 
     { 
      LOG.Error(webEx.StackTrace.ToString()); 
     } 
     catch (Exception ex) 
     { 
      LOG.Error(ex.StackTrace.ToString()); 
     } 
     finally 
     { 
      if (req != null) req.GetRequestStream().Close(); 
      if (rsp != null) rsp.GetResponseStream().Close(); 
     } 
+0

這與ASP.NET有什麼關係? – dtb

回答

2

您是否嘗試過使用req.ContentType = application/xml代替text/xml

+0

我有一個類似的問題,'req.ContentType = application/xml'不能解決它。 – Robert

相關問題