WCF 发送请求和接收响应

WCF to send request and receive response

我正在学习 WCF,我一直在使用网络服务 (.asmx) 向其他网络服务发送请求和接收响应。在网络服务上,我能够调用我的网络方法并测试它们。

 public string PrnNumber(string prnNumber)
    {
        bool flag = false;

        try
        {
            XmlDocument soapEnvelop = new XmlDocument();
            soapEnvelop.LoadXml(@"<SOAP-ENV:Envelope xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/1999/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/1999/XMLSchema""><SOAP-ENV:Body><HelloWorld xmlns=""http://tempuri.org/"" SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/""><int1 xsi:type=""xsd:integer"">12</int1><int2 xsi:type=""xsd:integer"">32</int2></HelloWorld></SOAP-ENV:Body></SOAP-ENV:Envelope>");
            flag = SendSOAP(soapEnvelop);
        }
        catch (Exception ex)
        {
            Util.LogMessage(ex.Message + ex.StackTrace, "Error", "err");
        }

        return "Success";
    }

    public bool SendSOAP(soapEnvelop)
    {
        bool flag = false;

        try
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http:***url");
            req.Headers.Add("Accept-Encoding", "gzip,deflate");
            req.Headers.Add("SOAPAction", "urn:lookupPRN");
            req.ContentType = "text/xml;charset=\"utf-8\"";
            req.Accept = "text/xml";
            req.Method = "POST";
            req.Proxy = null;


            try
            {
                using (Stream stm = req.GetRequestStream())
                {
                    using (StreamWriter stmw = new StreamWriter(stm))
                    {
                        stmw.Write(xml);
                    }
                }

                WebResponse response = req.GetResponse();

                Stream responseStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                string responseString = reader.ReadToEnd();
                Util.LogMessage(responseString, "Response", "res");

            }

            catch (Exception ex)
            {
                flag = false;
                Util.LogMessage(ex.Message + ex.StackTrace, "Error", "err");
            }
            return flag;
        }
        finally
        {

        }

    }

所以我最初是在 .asmx 中做的,我会记录请求和响应,我如何使用 WCF 实现这个?完全相同的逻辑,在我的代码中将 SOAP XML 构造为普通 XML 并调用合作伙伴的 url 进行响应。

建议您花一些时间复习几篇WCF“入门”文章。

以下提供了一个很好的基本概述:

https://docs.microsoft.com/en-us/dotnet/framework/wcf/getting-started-tutorial
http://www.codeproject.com/Articles/33995/Getting-Started-with-WCF
http://www.codeproject.com/Articles/42643/Creating-and-Consuming-Your-First-WCF-Service