构建原始ajax与wcf服务通讯



构建原始ajax与wcf服务通讯

这篇文章展示了客户端用xml、json格式来提交数据到服务器上,由 wcf 服务来处理。

Web.config 配置文件:

<system.serviceModel>
   <behaviors>
     <endpointBehaviors>
       <behavior name=”JsonXmlWcf.JsonXmlServiceAspNetAjaxBehavior”>
         <webHttp  />
       </behavior>
     </endpointBehaviors>
   </behaviors>
   <services>
     <service name=”JsonXmlWcf.JsonXmlService”>
       <endpoint address=”" behaviorConfiguration=”JsonXmlWcf.JsonXmlServiceAspNetAjaxBehavior”
           binding=”webHttpBinding” contract=”JsonXmlWcf.IJsonXmlService” />
     </service>
   </services>
</system.serviceModel>

JsonXmlService.svc 文件:

<%@ ServiceHost Language=”C#” Debug=”true” Service=”JsonXmlWcf.JsonXmlService” CodeBehind=”JsonXmlService.svc.cs” %>
JsonXmlService.svc.cs 文件:

using System;
using System.Text;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.ServiceModel.Channels;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
namespace JsonXmlWcf
{
   [ServiceContract(Namespace = "")]
   public interface IJsonXmlService
   {
       [OperationContract]
       [WebInvoke(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
       MyDataType JsonService(int id, string mytitle, string mycontent);

        [OperationContract(Action = "*")]
       [WebInvoke(ResponseFormat = WebMessageFormat.Xml, RequestFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
       Message XmlService(Message m);
   }

    public class JsonXmlService : IJsonXmlService
   {
       public MyDataType JsonService(int id, string mytitle, string mycontent)
       {
           return MyService(id, mytitle, mycontent, “以JSON形式传递”);
       }
       public Message XmlService(Message m)
       {
           return m;
       }
       private MyDataType MyService(int id, string mytitle, string mycontent, string info)
       {
           MyDataType MyData = new MyDataType();
           MyData.Id = id;
           MyData.MyTitle = string.Format(“{0}({1})”, mytitle, info);
           MyData.MyContent = mycontent;
           return MyData;
       }
   }

    [DataContract]
   public class MyDataType
   {
       private int _id;
       private string _mytitle;
       private string _content;

        [DataMember]
       public int Id
       {
           get { return _id; }
           set { _id = value; }
       }


        [DataMember]
       public string MyTitle
       {
           get { return _mytitle; }
           set { _mytitle = value; }
       }

        [DataMember]
       public string MyContent
       {
           get { return _content; }
           set { _content = value; }
       }
   }
}

客户端的调用(Default.htm ):

  <script language=”javascript” type=”text/javascript”>

        // 创建XMLHTTP
       function createXMLHTTP() {
           var httpRequest;
           try {
               httpRequest = new XMLHttpRequest();
           }
           catch (e) {
               try {
                   httpRequest = new ActiveXObject(“Msxml2.XMLHTTP”);
               }
               catch (e) {
                   try {
                       httpRequest = new ActiveXObject(“Microsoft.XMLHTTP”);
                   }
                   catch (e) {
                       return null;
                   }
               }
           }
           return httpRequest;
       }

        // 构造XML格式的文本
       function createXML() {
           var xml = ‘<?xml version=”1.0″ encoding=”utf-8″ ?>’
         + ‘<soap:Envelope xmlns:soap=”
http://schemas.xmlsoap.org/soap/envelope/” ‘
         + ‘xmlns:xsi=”
http://www.w3.org/2001/XMLSchema-instance” xmlns:xsd=”http://www.w3.org/2001/XMLSchema”>’
          + ‘<soap:Body>’
         + ‘<Id type=”number”>编号</Id>’
         + ‘<MyTitle type=”string”>标题</MyTitle>’
         + ‘<MyContent type=”string”>内容</MyContent>’
         + ‘</soap:Body></soap:Envelope>’;
           return xml;
       }

        // 构造JSON字符串
       function createJSON() {
           var json = ‘{“id”:1,”mytitle”:”标题”,”mycontent”:”内容”}’;
            return json;
       }

        // 异步调用服务器
       function callServer(postType) {
           var xmlHttp = createXMLHTTP();
           if (xmlHttp == null) { alert(‘浏览器不支持ajax’); return; }
           xmlHttp.onreadystatechange = function() {
               if (xmlHttp.readyState == 4) { callBack(xmlHttp.responseText) }
           }
           var body;
           var contentType;
           var url;
           if (postType == ‘json’) {
               body = createJSON();
               contentType = “application/json”;
               url = “/JsonXmlService.svc/JsonService”;
            }
           if (postType == ‘xml’) {
               body = createXML();
               contentType = “text/xml”;
               url = “/JsonXmlService.svc/XmlService”;
            }
           xmlHttp.open(“POST”, url, true);
           xmlHttp.setRequestHeader(“Content-type”, contentType);
           xmlHttp.send(body);
       }

        // 回调事件
       function callBack(responseText) {
           alert(responseText);
       }
   </script>
<body>
   <input type=”button” value=”以JSON方式提交” onclick=”callServer(‘json’);” />
   <br />
   <br />
   <input type=”button” value=”以XML方式提交” onclick=”callServer(‘xml’);” />
</body>

http://blog.sina.com.cn/s/articlelist_1483435013_0_1.html