Search code examples
c#base64wcf-rest

RESTful WCF receiving Base64 message. Need to convert message back to XML


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.


Solution

  • 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