Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# RESTful WCF接收Base64消息。需要将消息转换回XML_C#_Base64_Wcf Rest - Fatal编程技术网

C# RESTful WCF接收Base64消息。需要将消息转换回XML

C# RESTful WCF接收Base64消息。需要将消息转换回XML,c#,base64,wcf-rest,C#,Base64,Wcf Rest,我在尝试在RESTful WCF服务中编写代码时遇到了一些问题。我已经为调用的客户端应用程序提供了一个方法,并且我正在接收一条格式为Ax27834的消息。。。。。。这是一条Base64二进制消息。问题是,在收到此消息后,我需要能够将其转换回从客户端发送的消息的原始xml版本。如何在下面的代码片段中实现这一点。在下面的第6行,您将看到代码需要放在哪里。我一直在寻找解决办法,但没有找到任何合适的办法。我必须接收消息而不是流 我要强调的是,该服务在接收请求方面效果良好。我只是在努力将信息转换成我可以使

我在尝试在RESTful WCF服务中编写代码时遇到了一些问题。我已经为调用的客户端应用程序提供了一个方法,并且我正在接收一条格式为Ax27834的消息。。。。。。这是一条Base64二进制消息。问题是,在收到此消息后,我需要能够将其转换回从客户端发送的消息的原始xml版本。如何在下面的代码片段中实现这一点。在下面的第6行,您将看到代码需要放在哪里。我一直在寻找解决办法,但没有找到任何合适的办法。我必须接收消息而不是流

我要强调的是,该服务在接收请求方面效果良好。我只是在努力将信息转换成我可以使用的形式

接收代码

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());
}
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();
    }
  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);
    }
客户端代码

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());
}
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();
    }
  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);
    }
创建SOAP消息的代码

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());
}
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();
    }
  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);
    }
受保护的字符串CreateSoapMessage(字符串url、字符串操作、字符串消息内容)
{
返回字符串格式(
@"
{0}
“、消息内容、操作、url);
}

注意:TestNotice()对象包含一个大的xml字符串,它是消息的主体。

对于消息对象,您通常使用GetReaderAtBodyContents()获取主体内容的xml表示,除非您知道主体的类型,否则您可以使用GetBody。试着用这些来获取字符串,如果你仍然需要的话,然后解码它。您可以按如下方式执行此操作:

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

string message = System.Text.Encoding.Unicode.GetString(encodedMessageAsBytes);
从这里,您可以从字符串重构xml


编辑:要回答评论的最后一部分,内容类型应该是:text/xml

,不幸的是,这不起作用。我的信息格式为PD94BWGDMVYC2LV。。。。。。。。我得到了一个例外:输入不是有效的Base-64字符串,因为它包含一个非Base-64字符、两个以上的填充字符,或者填充字符中包含一个非法字符。对于这个错误,我能做些什么吗?我还应该注意,如果不执行ToString(),消息对象不能像您所示那样简单地放入该函数中,这可能会产生错误My bad:(看得不够仔细,我假设您得到的是一个字符串对象。内容类型不应该是:text/xml吗?很高兴为您解决了这个问题……。一双新眼睛能做的事情真是太神奇了……。即使他们在开始时错过了消息对象:)