0

now i try to call web service in local server from windows service but i have error the error is "The request was aborted: The request was canceled." my code is

try {
XmlDocument soapEnvelopeXml = new XmlDocument();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("xx.asmx");
request.UserAgent = "Mozilla/5.0";
request.Host = "server";
request.ContentType = "text/xml; charset=utf-8";
request.Headers.Add("SOAPAction", "\"xx\"");
request.Method = "POST";
request.Accept = "text/xml";

soapEnvelopeXml.LoadXml(getXml(dt));
request.ContentLength = soapEnvelopeXml.OuterXml.Length;
using (Stream Stream = request.GetRequestStream()) {
    soapEnvelopeXml.Save(Stream);
}
using (WebResponse response = request.GetResponse()) {

    using (StreamReader rd = new StreamReader(response.GetResponseStream())) {
        string soapResalt = rd.ReadToEnd();
        CtlCommon.CreateErrorLog(strPath, soapResalt);
    }
}


} catch (Exception ex) {
    CtlCommon.CreateErrorLog(strPath, ex.InnerException.ToString);
    CtlCommon.CreateErrorLog(strPath, ex.Message);
}

some time i try to close Stream, StreamReader and response but the error still exist

Ibrahim Alsurkhi
  • 113
  • 1
  • 13

2 Answers2

4

I faced the issue because of the Norwegian special characters (e.g. Ø, å, etc.) being sent across. Resolved it by using the UTF-8 encoding.

Send the data using the UTF-8 encoding. You can refer to the following C# code as sample for UTF-8 encoding.

httpWebRequest.ContentType      = "text/xml; charset=utf-8";
httpWebRequest.Method           = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(xmlData);   //Convert to UTF-8
httpWebRequest.ContentLength = byteArray.Length;      //Set the length of UTF-8 format

//Send the data in UTF-8 format
using (Stream streamWriter = httpWebRequest.GetRequestStream())
{
    streamWriter.Write(byteArray, 0, byteArray.Length);
    streamWriter.Flush();
}

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();         
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    ret = streamReader.ReadToEnd();
}
Aman
  • 41
  • 3
  • This is the best solution that fixed, "The request was aborted: The request was canceled", issue. 1. You have to convert the data to be sent to a UTF-8 encoded Byte array. 2. You have to use System.IO.Stream class (not StreamWriter) which allows you to send the Byte array I had to make note of this because, like a d00fus, I tried to convert the Byte array to a Char array and kept getting the error while using a StreamWriter object! – cChacon Sep 28 '22 at 20:08
0

The issue I had was french letters like Élie --- had to use ASCII encoding.

kiev
  • 2,040
  • 9
  • 32
  • 54