学习 WCF (6)--学习调用WCF服务的各种方法
根據(jù)不同的情況,我們可以用不同的方法調(diào)用WCF服務(wù),本文簡(jiǎn)單總結(jié)了一下調(diào)用WCF的一些方法(代理類(lèi),Ajax...),分享給大家。開(kāi)發(fā)工具調(diào)用WCF
這中方法很方便也很簡(jiǎn)單,很多工作VS就幫我們完成了。相信大家也不會(huì)對(duì)這種方法陌生。這里簡(jiǎn)單提一下。打開(kāi)VS,在項(xiàng)目中添加服務(wù)引用:
在config中自動(dòng)聲明了有關(guān)服務(wù)的節(jié)點(diǎn)信息,這樣VS就創(chuàng)建了調(diào)用服務(wù)的代理: ServiceReference1.Service1Client?poxy?=newServiceReference1.Service1Client();
poxy.服務(wù)中相應(yīng)的方法。
C#動(dòng)態(tài)調(diào)用WCF
這個(gè)方法比較實(shí)用,可以通過(guò)工具或代碼生成代理類(lèi)Proxy.cs,來(lái)和WCF進(jìn)行交互。不需要人為的手動(dòng)進(jìn)行服務(wù)的引用。生成代理類(lèi),這里我里用了工具:SvcUtil.exe,沒(méi)有的朋友可以下載:SvcUtil.rar
使用方法很簡(jiǎn)單,只需將SvcUtil.exe隨便放置一個(gè)位置(這里放在C:/新建文件夾)。在命令提示行中輸入如下指令:
這里要注意的是SvcUtil.exe后面是服務(wù)的地址,會(huì)在工具所在的目錄下生成代理類(lèi)文件:
工具會(huì)給我們生成一個(gè)代理類(lèi)文件,代碼如下: Code//------------------------------------------------------------------------------//?<auto-generated>//?????此代碼由工具生成。//?????運(yùn)行庫(kù)版本:2.0.50727.1433////?????對(duì)此文件的更改可能會(huì)導(dǎo)致不正確的行為,并且如果//?????重新生成代碼,這些更改將會(huì)丟失。//?</auto-generated>//------------------------------------------------------------------------------namespace?LtraSrchLib.DAL
{using?System.Runtime.Serialization;
????[System.Diagnostics.DebuggerStepThroughAttribute()]
????[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization",?"3.0.0.0")]
????[System.Runtime.Serialization.DataContractAttribute(Name="DbModal",?Namespace="http://schemas.datacontract.org/2004/07/LtraSrchLib.DAL")]public?partial?class?DbModal?:?object,?System.Runtime.Serialization.IExtensibleDataObject
????{private?System.Runtime.Serialization.ExtensionDataObject?extensionDataField;private?string?ArtReferenceField;private?string?ArticalLevelField;private?string?ChineseAbstractField;private?string?ChineseKeywordField;private?string?ChineseTitleField;private?string?DownLoadPathField;private?string?EnglishAbstractField;private?string?EnglishKeywordField;private?string?EnglishTitleField;private?string?FileClassField;private?string?IdField;private?string?PageNumField;private?string?PublishedDateField;private?string?SchoolField;private?string?SpecialtyField;private?string?StateField;private?string?StudentNameField;private?string?StudentNumField;private?string?StudyToField;private?string?TeacherField;private?string?UpLoadDateField;public?System.Runtime.Serialization.ExtensionDataObject?ExtensionData
????????{get
????????????{return?this.extensionDataField;
????????????}set
????????????{this.extensionDataField?=?value;
????????????}
????????}
????????[System.Runtime.Serialization.DataMemberAttribute()]public?string?ArtReference
????????{get
????????????{return?this.ArtReferenceField;
????????????}set
????????????{this.ArtReferenceField?=?value;
????????????}
????????}
????????[System.Runtime.Serialization.DataMemberAttribute()]public?string?ArticalLevel
????????{get
????????????{return?this.ArticalLevelField;
????????????}set
????????????{this.ArticalLevelField?=?value;
????????????}
????????}
????????[System.Runtime.Serialization.DataMemberAttribute()]public?string?ChineseAbstract
????????{get
????????????{return?this.ChineseAbstractField;
????????????}set
????????????{this.ChineseAbstractField?=?value;
????????????}
????????}
????????[System.Runtime.Serialization.DataMemberAttribute()]public?string?ChineseKeyword
????????{get
????????????{return?this.ChineseKeywordField;
????????????}set
????????????{this.ChineseKeywordField?=?value;
????????????}
????????}
????????[System.Runtime.Serialization.DataMemberAttribute()]public?string?ChineseTitle
????????{get
????????????{return?this.ChineseTitleField;
????????????}set
????????????{this.ChineseTitleField?=?value;
????????????}
????????}
????????[System.Runtime.Serialization.DataMemberAttribute()]public?string?DownLoadPath
????????{get
????????????{return?this.DownLoadPathField;
????????????}set
????????????{this.DownLoadPathField?=?value;
????????????}
????????}
????????[System.Runtime.Serialization.DataMemberAttribute()]public?string?EnglishAbstract
????????{get
????????????{return?this.EnglishAbstractField;
????????????}set
????????????{this.EnglishAbstractField?=?value;
????????????}
????????}
????????[System.Runtime.Serialization.DataMemberAttribute()]public?string?EnglishKeyword
????????{get
????????????{return?this.EnglishKeywordField;
????????????}set
????????????{this.EnglishKeywordField?=?value;
????????????}
????????}
????????[System.Runtime.Serialization.DataMemberAttribute()]public?string?EnglishTitle
????????{get
????????????{return?this.EnglishTitleField;
????????????}set
????????????{this.EnglishTitleField?=?value;
????????????}
????????}
????????[System.Runtime.Serialization.DataMemberAttribute()]public?string?FileClass
????????{get
????????????{return?this.FileClassField;
????????????}set
????????????{this.FileClassField?=?value;
????????????}
????????}
????????[System.Runtime.Serialization.DataMemberAttribute()]public?string?Id
????????{get
????????????{return?this.IdField;
????????????}set
????????????{this.IdField?=?value;
????????????}
????????}
????????[System.Runtime.Serialization.DataMemberAttribute()]public?string?PageNum
????????{get
????????????{return?this.PageNumField;
????????????}set
????????????{this.PageNumField?=?value;
????????????}
????????}
????????[System.Runtime.Serialization.DataMemberAttribute()]public?string?PublishedDate
????????{get
????????????{return?this.PublishedDateField;
????????????}set
????????????{this.PublishedDateField?=?value;
????????????}
????????}
????????[System.Runtime.Serialization.DataMemberAttribute()]public?string?School
????????{get
????????????{return?this.SchoolField;
????????????}set
????????????{this.SchoolField?=?value;
????????????}
????????}
????????[System.Runtime.Serialization.DataMemberAttribute()]public?string?Specialty
????????{get
????????????{return?this.SpecialtyField;
????????????}set
????????????{this.SpecialtyField?=?value;
????????????}
????????}
????????[System.Runtime.Serialization.DataMemberAttribute()]public?string?State
????????{get
????????????{return?this.StateField;
????????????}set
????????????{this.StateField?=?value;
????????????}
????????}
????????[System.Runtime.Serialization.DataMemberAttribute()]public?string?StudentName
????????{get
????????????{return?this.StudentNameField;
????????????}set
????????????{this.StudentNameField?=?value;
????????????}
????????}
????????[System.Runtime.Serialization.DataMemberAttribute()]public?string?StudentNum
????????{get
????????????{return?this.StudentNumField;
????????????}set
????????????{this.StudentNumField?=?value;
????????????}
????????}
????????[System.Runtime.Serialization.DataMemberAttribute()]public?string?StudyTo
????????{get
????????????{return?this.StudyToField;
????????????}set
????????????{this.StudyToField?=?value;
????????????}
????????}
????????[System.Runtime.Serialization.DataMemberAttribute()]public?string?Teacher
????????{get
????????????{return?this.TeacherField;
????????????}set
????????????{this.TeacherField?=?value;
????????????}
????????}
????????[System.Runtime.Serialization.DataMemberAttribute()]public?string?UpLoadDate
????????{get
????????????{return?this.UpLoadDateField;
????????????}set
????????????{this.UpLoadDateField?=?value;
????????????}
????????}
????}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel",?"3.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(ConfigurationName="ISrchLib")]public?interface?ISrchLib
{
????[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/ISrchLib/SelNoteBySql",?ReplyAction="http://tempuri.org/ISrchLib/SelNoteBySqlResponse")]
????LtraSrchLib.DAL.DbModal[]?SelNoteBySql(string?ServiceName,?string?InfoStr);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel",?"3.0.0.0")]public?interface?ISrchLibChannel?:?ISrchLib,?System.ServiceModel.IClientChannel
{
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel",?"3.0.0.0")]public?partial?class?SrchLibClient?:?System.ServiceModel.ClientBase<ISrchLib>,?ISrchLib
{public?SrchLibClient()
????{
????}public?SrchLibClient(string?endpointConfigurationName)?:?base(endpointConfigurationName)
????{
????}public?SrchLibClient(string?endpointConfigurationName,?string?remoteAddress)?:?base(endpointConfigurationName,?remoteAddress)
????{
????}public?SrchLibClient(string?endpointConfigurationName,?System.ServiceModel.EndpointAddress?remoteAddress)?:?base(endpointConfigurationName,?remoteAddress)
????{
????}public?SrchLibClient(System.ServiceModel.Channels.Binding?binding,?System.ServiceModel.EndpointAddress?remoteAddress)?:?base(binding,?remoteAddress)
????{
????}public?LtraSrchLib.DAL.DbModal[]?SelNoteBySql(string?ServiceName,?string?InfoStr)
????{return?base.Channel.SelNoteBySql(ServiceName,?InfoStr);
????}
}
把這個(gè)代理類(lèi)考到客戶(hù)端程序就可以對(duì)WCF進(jìn)行調(diào)用了,這里建議大家用工具生成,自己手寫(xiě)可能會(huì)出現(xiàn)錯(cuò)誤,生成后如果做稍許的改動(dòng),都可能造成錯(cuò)誤,影響到信道數(shù)據(jù)的傳輸。(但是這里說(shuō)明一下:這個(gè)工具在xp下使用沒(méi)問(wèn)題,但是在2003下使用會(huì)有問(wèn)題,不知是不是我2003統(tǒng)的問(wèn)題)
停在這里就不動(dòng)了,不知為啥。
大家這里可能會(huì)想到用代碼生成代理類(lèi)的方法,但是我試了幾次沒(méi)有成功,文件生成了但是沒(méi)有內(nèi)容。不知道為什么。高手指點(diǎn)。
有了這個(gè)代理類(lèi),工作就好做啦!通過(guò)這個(gè)代理類(lèi)就可以調(diào)用WCF了。 Codeprivate?void?CreateClientInstanceByProxy(Binding?bind,?EndpointAddress?address,?string?a,?string?b)
{
?????ISrchLib?ws?=?new?SrchLibClient(bind,?address);//傳入binding和服務(wù)的URI
?????Repeater1.DataSource?=?ws.SelNoteBySql(a,?b);//a,b是服務(wù)中方法的參數(shù)?????Repeater1.DataBind();
}
這樣,如果多個(gè)服務(wù)的方法相同,只是address不同(分布在不同的服務(wù)器)。這樣的調(diào)用是很不錯(cuò)的選擇!
除此之外,我們可以采用通道工廠的方式生成客戶(hù)端服務(wù)對(duì)象實(shí)例,但是前提還是需要上面生成的代理類(lèi)的幫助。大家可以參看大牛Robin的文章(下面有鏈接)。ASP.NET AJAX調(diào)用WCF
利用ASP.NET AJAX調(diào)用WCF:
我們新建網(wǎng)站一個(gè)工程,在其添加啟用了Ajax的WCF服務(wù)。這樣配置文件中會(huì)自動(dòng)的為我們添加關(guān)鍵的節(jié)點(diǎn)。
服務(wù)中我只是簡(jiǎn)單的聲明了一個(gè)方法: Codepublic?class?ajaxService
{//?添加?[WebGet]?屬性以使用?HTTP?GET????[OperationContract]public?void?DoWork()
????{return;
????}
????[OperationContract]public?string?SayHello(string?name)
????{return?"hello:"+name;
????}//?在此處添加更多操作并使用?[OperationContract]?標(biāo)記它們}
在瀏覽器中預(yù)覽我們的服務(wù),然后在地址后加上/js。這樣就可以生成用來(lái)訪問(wèn)WCF的js代理。
生成js代碼:再來(lái)看一下前臺(tái)頁(yè)面中的代碼: Code<html?xmlns="http://www.w3.org/1999/xhtml"><head?runat="server"><title>無(wú)標(biāo)題頁(yè)</title><script?type="text/javascript">function?sayhello()
????{var?name?=?$get("txtname").value;
??????ajaxService.SayHello(name,onSuccess,onFailed);??????
????}function?onSuccess(res)
????{
???????alert(res);
????}function?onFailed(res)
????{
????????alert(res);
????}</script></head><body><form?id="form1"?runat="server"><div><asp:ScriptManager?ID="ScriptManager1"?runat="server"><Scripts><asp:ScriptReference?Path="~/js/ajaxwcf.js"?/>????????????</Scripts></asp:ScriptManager></div><div><p>name:<input?id="txtname"?type="text"?/></p><p><input?id="Button1"?type="button"?value="hello"??onclick="sayhello()"/></p></div></form></body></html>
將ScriptManager中的<script>的path設(shè)定為剛生成的js文件。這樣,腳本中聲明的方法就可以調(diào)用WCF的方法了。運(yùn)行一下:
這樣就實(shí)現(xiàn)了ASP.NET AJAX對(duì)WCF的調(diào)用。JS(jQuery)調(diào)用WCF
這里實(shí)現(xiàn)的思想和ASP.NET Ajax的有些類(lèi)似,只不過(guò)有一些工作需要我們自己來(lái)完成,并且這個(gè)方法很靈活。
首先是WCF上:我們要在類(lèi)和方法前進(jìn)行如下的聲明:
????[AspNetCompatibilityRequirements(RequirementsMode?=?AspNetCompatibilityRequirementsMode.Allowed)]public?class?WCFservice
????{
????????[OperationContract]
????????[WebInvoke(RequestFormat?=?WebMessageFormat.Json,?ResponseFormat?=?WebMessageFormat.Json,?BodyStyle?=?WebMessageBodyStyle.WrappedRequest)]public?string?SayHello(string?name)
????????{return?"hello:"+name;
????????}
????}
接著就是配置文件:
Code<system.serviceModel><behaviors><endpointBehaviors><behavior?name="AllenBehavior"><enableWebScript?/></behavior></endpointBehaviors></behaviors><serviceHostingEnvironment?aspNetCompatibilityEnabled="true"?/><services><service?name="jqueryWCF.WCFservice"><endpoint?address=""?behaviorConfiguration="AllenBehavior"?binding="webHttpBinding"?contract="jqueryWCF.WCFservice"?/></service></services></system.serviceModel><behavior name="AllenBehavior"><enableWebScript /></behavior>
準(zhǔn)備工作做好后就可以前臺(tái)調(diào)用了:
????$.ajax({
????????type:?'post',
????????url:?'/WCFservice.svc/SayHello',
????????contentType:?'text/json',
????????data:?'{"name":"'+name+'"}',
????????success:?function(msg)?{var?a?=?eval('('+msg+')');if(String(a.d).length>0){alert(a.d);}else{alert("服務(wù)器超時(shí)");}
????????}
????});
????}</script><style?type="text/css">
#content{height:?181px;width:?549px;}
#title{width:?544px;}</style></head><body><form?id="form1"?runat="server"><div>
????????name:<input?type="text"?id="name"?/><br?/><input?type="button"??value="hello"?onclick="sayhello();"?/></div></form></body></html>
這里的一些注意事項(xiàng)大家可以但看dudu的文章(下面有鏈接)。這樣,我們就可以利用jQuery調(diào)用wcf了。
小結(jié):以上就是調(diào)用WCF的一些方法,希望對(duì)大家學(xué)習(xí)WCF有幫助。也希望大家分享其他調(diào)WCF的方法。
參考學(xué)習(xí)資料:
Robin:http://www.cnblogs.com/jillzhang/archive/2008/07/26/1252171.html
dudu:http://www.cnblogs.com/dudu/archive/2009/07/14/1523082.htmlliulun:http://www.cnblogs.com/liulun/articles/1425382.html
總結(jié)
以上是生活随笔為你收集整理的学习 WCF (6)--学习调用WCF服务的各种方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 小雪花歌曲视频(小雪花歌曲简谱)
- 下一篇: 分享WCF聊天程序--WCFChat