WCF发送请求和接收响应

时间:2015-02-03 14:25:04

标签: c# web-services wcf soap

在学习WCF时,我一直在使用webservices(.asmx)发送请求并接收对其他Web服务的响应。在webservices上,我能够调用我的webmethods并测试它们。

 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。