0

I am having some trouble trying to write code within a RESTful WCF service. I have made a method available to a calling client application and I am receiving a message that is of the format Ax27834...... which is a Base64 Binary message. The issue is that following receiving this I need to be able to convert it back to the original xml version of that message that was sent from the client. How can I achieve this in the code snippet below. On line 6 below you will see where the code needs to go. I have searched for a solution but not managed to find anything suitable. I have to receive a message rather than a stream.

I should highlight that the service works fine in the respect of receiving the request. I am just struggling to get the message into a form that I can use.

The receiving code

public Message StoreMessage(Message request)
{
    //Store the message
    try
        {
        string message = [NEED SOLUTION HERE]

        myClass.StoreNoticeInSchema(message, DateTime.Now);
    }
    catch (Exception e)
    {
        log4net.Config.XmlConfigurator.Configure();

        ILog log = LogManager.GetLogger(typeof(Service1));

        if (log.IsErrorEnabled)
        {
            log.Error(String.Format("{0}: Notice was not stored. {1} reported an exception. {2}", DateTime.Now, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, e.Message));
        }
    }

    XElement responseElement = new XElement(XName.Get("elementName", "url"));

    XDocument resultDocument = new XDocument(responseElement);

    return Message.CreateMessage(OperationContext.Current.IncomingMessageVersion, "elementName", resultDocument.CreateReader());
}

The client code

public string CallPostMethod()
    {
        const string action = "StoreNotice/New";

        TestNotice testNotice = new TestNotice();

        const string url = "http://myaddress:myport/myService.svc/StoreNotice/New";

        string contentType = String.Format("application/soap+xml; charset=utf-8; action=\"{0}\"", action);
        string xmlString = CreateSoapMessage(url, action, testNotice.NoticeText);

        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

        ASCIIEncoding encoding = new ASCIIEncoding();

        byte[] bytesToSend = encoding.GetBytes(xmlString);

        request.Method = "POST";
        request.ContentLength = bytesToSend.Length;
        request.ContentType = contentType;

        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(bytesToSend, 0, bytesToSend.Length);
            requestStream.Close();
        }

        string responseFromServer;

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        using (Stream dataStream = response.GetResponseStream())
        {
            using (StreamReader reader = new StreamReader(dataStream))
                responseFromServer = reader.ReadToEnd();
            dataStream.Close();
        }

        XDocument document = XDocument.Parse(responseFromServer);
        string nameSpace = "http://www.w3.org/2003/05/soap-envelope";
        XElement responseElement = document.Root.Element(XName.Get("Body", nameSpace))
                                             .Element(XName.Get(@action + "Response", "http://www.wrcplc.co.uk/Schemas/ETON"));


        return responseElement.ToString();
    }

Code to create SOAP message

  protected string CreateSoapMessage(string url, string action, string messageContent)
    {
        return String.Format(
 @"<?xml version=""1.0"" encoding=""utf-8""?>
 <soap12:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" 
 xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap12=""http://www.w3.org/2003/05/soap-envelope""><soap12:Body>{0}</soap12:Body>
</soap12:Envelope>
", messageContent, action, url);
    }

NOTE: The TestNotice() object contains a large xml string which is the body of the message.

CSharpened
  • 11,674
  • 14
  • 52
  • 86

1 Answers1

0

With a Message object you usually use GetReaderAtBodyContents() to get an XML representation of the body content, unless you know what type the body has then you can use GetBody<>. Try using those to get the string, and then decode it if you still need to. Which you can do as follows:

byte[] encodedMessageAsBytes = System.Convert.FromBase64String(requestString);

string message = System.Text.Encoding.Unicode.GetString(encodedMessageAsBytes);

From there you can reconstruct the xml from the string

Edit: to answer the last part from the comment, the content type should be: text/xml

JTMon
  • 3,189
  • 22
  • 24
  • Unfortunately this doesnt work. My Message takes the form PD94bWwgdmVyc2lv........ and I get the exception: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters. Is there something I can do about this error? – CSharpened Sep 04 '12 at 13:24
  • I should also note that the message object cannot simply be put into that function as you have shown without performing a ToString() which may be producing this error – CSharpened Sep 04 '12 at 13:27
  • How about if you strip the .... from the message before proceeding with the decoding? Wouldn't that solve the error you just mentioned? – JTMon Sep 04 '12 at 13:30
  • 1
    My bad :( did not look closely enough and I assumed you were getting a string object – JTMon Sep 04 '12 at 13:32
  • I get this result from stripping the tags and converting ;) 㼼浸敶獲潩㵮ㄢ〮•湥潣楤杮∽瑵ⵦ∸㸿਍猼慯ㅰ㨲湅敶潬数砠汭獮砺楳∽瑨灴⼺眯睷眮⸳牯⽧〲㄰堯䱍捓敨慭椭獮慴据≥砠汭獮 – CSharpened Sep 04 '12 at 13:34
  • Are you sure that is now what it is supposed to look like? :) I have edited my post to address a Message object instead of a string :) – JTMon Sep 04 '12 at 13:49
  • I have tried the edit but I only get and empty string. I have now updated my original question to showt he client code that does the sending. Is there anything in there that you can see that may cause an issue? – CSharpened Sep 04 '12 at 14:04
  • 1
    Shouldn't the content type be: text/xml? – JTMon Sep 04 '12 at 14:22
  • Legend. I feel like slapping myself very hard round the face now. Thanks. Add that to your answer. I have selected it as the answer. – CSharpened Sep 04 '12 at 14:26
  • 1
    Glad to have helped solve it for you....... it is amazing what a fresh set of eyes can do........ even if they missed the Message object in the beginning :) – JTMon Sep 04 '12 at 14:30