Ajax调用RESTful WCF
2015-05-11 22:47
267 查看
这几天在学习RESTful WCF 感觉调用起来比较舒服,就是不能在vs里面直接生成类了。。。
首先是RESTful WCF的构建
.svc 后面要加上
先是接口文件:
然后是实现文件
解释一下
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是两个都包装。
然后是传送的类:
如果想要在json中加入一个字段 就用 DataMember 来标记。如果不加DataMember,json中是看不见这个字段的!而且是否可见跟private public无关。
Order为转换为json的时候,字段的顺序。当有Order的时候,小的在前面
结果就是{“str”:”Invoke Success!”,”num”:1,”ok”:true}
然后貌似不加Order的在加Order的前面(这个不确定,做了几次试验貌似是这样)
如果是基本类型(比如bool什么的)而且没有选择包装Response的时候就是单纯的值,并没有json格式
然后是配置文件
配置文件一定要认真的检查有没有漏的,因为配置文件写错了不是服务直接挂了就是访问不到。。。
然后是如何用Ajax调用WCF了。。。
如果用jQuery的话,就是$.ajax()
POST:
GET
注意url这三个字母不能大写-_-||
如果手写ajax的话
注意先设置onreadystatechange 的处理函数再send就行了~
至于在C#客户端那面就可以用WebHttpRequest和WebHttpResponse来处理
GET
POST
首先是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, RequestFormat = 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, 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); } });
注意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", url, 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()); }
相关文章推荐
- js调用本地摄像头截图并用ajax上传至后台服务器完成交互
- ASP.NET 2.0 AJAX中Webservice调用方法
- AJAX调用方式总结(3)
- Ajax的同步调用场景——使用同步Ajax在 onunload 事件时通知服务器
- Extjs/Ajax中的success和failure 何时调用?
- ASP.NET AJAX中Webservice调用方法示例
- .net ajax 异步调用的几种实现方法(jquery)
- AJAX 调用 WEBSERVICE的例子,包括对XML数据的处理,包含源码下载
- JS脚本使用AJAX调用远程服务后获取返回的错误信息
- ajax 调用服务端方法时data类型需要与服务器一致
- AJAX调用百度API
- 在页面没有完全加载完毕前调用Ajax方法会出错
- ASP.Net Ajax应用初步:使用AJAX调用WebService
- SpringBoot 调用ajax POST 方法报Request method 'POST' not supported解决方法
- PHP中如何防止外部恶意提交调用ajax接口
- 不用AJAX实现前台JS调用后台C#方法
- 实现ajax和json的调用
- click 中 有ajax调用多次的情况
- Ajax使用PageMethods调用后台方法
- Ajax基石脚本异步并发调用参数传递