Ajax调用RESTful WCF

这几天在学习RESTful WCF 感觉调用起来比较舒服,就是不能在vs里面直接生成类了。。。
首先是RESTful WCF的构建

.svc 后面要加上

Factory="System.ServiceModel.Activation.WebServiceHostFactory

先是接口文件

[ServiceContract]
public interface ITestWCF
{
    [OperationContract]
    [WebGet(ResponseFormat = Webmessageformat.Json,UriTemplate = "DoWork")]
    bool DoWork();

    [OperationContract]
    [WebInvoke(ResponseFormat = Webmessageformat.Json,BodyStyle = WebMessageBodyStyle.Wrapped,UriTemplate = "WebInvokeWithNoArgs",Method = "POST")]
    ReturnObj WebInvokeWithNoArgs();

    [OperationContract]
    [WebInvoke(ResponseFormat = Webmessageformat.Json,RequestFormat =Webmessageformat.Json,BodyStyle =WebMessageBodyStyle.WrappedRequest,UriTemplate = "WebInvokeWithArgs",Method = "POST")]
    ReturnObj WebInvokeWithArgs(string str);

    [OperationContract]
    [WebGet(ResponseFormat = Webmessageformat.Json,RequestFormat = Webmessageformat.Json,UriTemplate = "WebGetWithNoArgs")]
    ReturnObj WebGetWithNoArgs();

    [OperationContract]
    [WebGet(ResponseFormat = Webmessageformat.Json,UriTemplate = "WebGetWithArgs/{str}")]
    ReturnObj WebGetWithArgs(string str);
}

然后是实现文件

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class TestWCF : ITestWCF
{
    public bool DoWork()
    {
        return true;
    }

    public ReturnObj WebGetWithArgs(string str)
    {
        return new ReturnObj(str);
    }

    public ReturnObj WebGetWithNoArgs()
    {
        return new ReturnObj("Get Success!");
    }

    public ReturnObj WebInvokeWithArgs(string str)
    {
        return new ReturnObj(str);
    }

    public ReturnObj WebInvokeWithNoArgs()
    {
        return new ReturnObj("Invoke Success!");
    }
}

解释一下
WebInvoke 跟WebGet的区别可以理解为 一个是POST,一个是GET。但是WebInvoke的Method也可以为GET,WebGet只能是Get
ResponseFormat = Webmessageformat.Json 这个就是Response的时候采用Json的方式
UriTemplate 这个可以理解一个地址 比如 UriTemplate = “WebInvokeWithNoArgs” 你可以用 http://xxx.xxx.xxx/xxx.svc/WebInvokeWithNoArgs 来进行访问。
当Method为GET,且有参数的时候,可以采用UriTemplate =“方法地址/{参数}/{参数}”的方式来向WCF传递参数。当然,POST还是老老实实写Json吧~
BodyStyle =WebMessageBodyStyle.WrappedRequest 这个为包装Request,这个笔者也没有弄清具体的功能,只是没有这句话的时候 ajax返回的 status为200 加上就好了。。。
BodyStyle = WebMessageBodyStyle.WrappedResponse 这个为包装Response,就是在ajax得到Json的时候会有{“WebInvokeWithNoArgsResult”:{“str”:”Invoke Success!”}}(有) {“str”:”Invoke Success!”}(无)
WebMessageBodyStyle还有两个就是Bare和Wrapped。Bare是全不包装,Wrapped是两个都包装。

然后是传送的类:

[DataContract]
public class ReturnObj
{
    [DataMember(Order = 0)]
    public string str;
    public ReturnObj(string args)
    {
        str = args;
    }
}

如果想要在json中加入一个字段 就用 DataMember 来标记。如果不加DataMember,json中是看不见这个字段的!而且是否可见跟private public无关。
Order为转换为json的时候,字段的顺序。当有Order的时候,小的在前面

[DataMember(Order = 0)]
    private string str;
    [DataMember(Order = 1)]
    public int num;
    [DataMember(Order = 2)]
    public bool ok;

结果就是{“str”:”Invoke Success!”,”num”:1,”ok”:true}
然后貌似不加Order的在加Order的前面(这个不确定,做了几次试验貌似是这样)

如果是基本类型(比如bool什么的)而且没有选择包装Response的时候就是单纯的值,并没有json格式

然后是配置文件

<system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="TestWCFBehavior"></behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    <services>
      <service name="TestWCF">
        <endpoint address="" behaviorConfiguration="TestWCFBehavior" binding="webHttpBinding" contract="ITestWCF"></endpoint>
      </service>
    </services>
  </system.serviceModel>

配置文件一定要认真的检查有没有漏的,因为配置文件写错了不是服务直接挂了就是访问不到。。。

然后是如何用Ajax调用WCF了。。。
如果用jQuery的话,就是$.ajax()
POST:

$.ajax({
            url: "../TestWCF.svc/WebInvokeWithArgs",type: "POST",contentType: "text/json",asnyc: "false",data: '{"str":"Invoke Test"}',dataType: 'json',success: function (resultObj) {
                var resultStr = String(JSON.stringify(resultObj));
                alert(resultStr);
            },error: function (XMLHttpRequest,textStatus,errorThrown) {
                alert(XMLHttpRequest.status);
                alert(XMLHttpRequest.readyState);
                alert(textStatus);
            }
        });

GET

$.ajax({
            url: "TestWCF.svc/WebGetWithArgs/Get Test",type: "Get",asnyc: false,errorThrown) {
                alert(XMLHttpRequest.status);
                alert(XMLHttpRequest.readyState);
                alert(textStatus);
            }
        });

注意url这三个字母不能大写-_-||

如果手写ajax的话

<script type="text/javascript"> var xmlHttp; //下面这个函数根据是否为IE浏览器来生成不同ajax对象 function createxmlHttpRequest() { if (window.ActiveXObject) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } else if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } } //POST function doPost() { var url = "TestWCF.svc/WebInvokeWithArgs"; var data = '{"str":"Invoke Test"}';//注意为json格式 createxmlHttpRequest(); xmlHttp.open("POST",url,false);//open(方法,地址,同步) xmlHttp.setRequestHeader("Content-Type","text/json"); xmlHttp.onreadystatechange = function () { if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200)) { alert(xmlHttp.responseText); } else { alert(xmlHttp.status); } } xmlHttp.send(data); return false; } //GET function doGet() { var url = "TestWCF.svc/WebGetWithNoArgs"; createxmlHttpRequest(); xmlHttp.onreadystatechange = function () { if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200)) { alert(xmlHttp.responseText); } else { alert(xmlHttp.status); } } xmlHttp.open("GET",false); xmlHttp.send(""); return false; } </script>

注意先设置onreadystatechange 的处理函数再send就行了~

至于在C#客户端那面就可以用WebHttpRequest和WebHttpResponse来处理
GET

static void Main(string[] args)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:65143/testwcf.svc/WebGetWithNoArgs");
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader sr = new StreamReader(res.GetResponseStream());
            Console.WriteLine(sr.ReadToEnd());

        }

POST

static void Main(string[] args)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:65143/testwcf.svc/WebInvokeWithArgs");
            req.Method = "POST";
            req.ContentType = "application/json";
            string data = @"{""str"":""From C#""}";
            byte[] SendData = Encoding.Default.GetBytes(data);
            req.ContentLength = SendData.Length;
            req.GetRequestStream().Write(SendData,0,SendData.Length);
            req.GetRequestStream().Close();
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader sr = new StreamReader(res.GetResponseStream());
            Console.WriteLine(sr.ReadToEnd());

        }

相关文章

IE6是一个非常老旧的网页浏览器,虽然现在很少人再使用它,但...
PHP中的count()函数是用来计算数组或容器中元素的个数。这个...
使用 AJAX(Asynchronous JavaScript and XML)技术可以在不...
Ajax(Asynchronous JavaScript and XML)是一种用于改进网页...
本文将介绍如何通过AJAX下载Excel文件流。通过AJAX,我们可以...
Ajax是一种用于客户端和服务器之间的异步通信技术。通过Ajax...