來自:http://www.cnblogs.com/gaoweipeng/archive/2009/07/26/1528263.html
根據不同的情況,我們可以用不同的方法調用WCF服務,本文簡單總結了一下調用WCF的一些方法(代理類,Ajax...),分享給大家。
開發工具調用WCF
這中方法很方便也很簡單,很多工作VS就幫我們完成了。相信大家也不會對這種方法陌生。這里簡單提一下。打開VS,在項目中添加服務引用:
在config中自動聲明了有關服務的節點信息,這樣VS就創建了調用服務的代理:
poxy.服務中相應的方法。
C#動態調用WCF
這個方法比較實用,可以通過工具或代碼生成代理類Proxy.cs,來和WCF進行交互。不需要人為的手動進行服務的引用。生成代理類,這里我里用了工具:SvcUtil.exe,沒有的朋友可以下載:SvcUtil.rar
使用方法很簡單,只需將SvcUtil.exe隨便放置一個位置(這里放在C:/新建文件夾)。在命令提示行中輸入如下指令:
這里要注意的是SvcUtil.exe后面是服務的地址,會在工具所在的目錄下生成代理類文件:
工具會給我們生成一個代理類文件,代碼如下:


//------------------------------------------------------------------------------
//?<auto-generated>
//?????此代碼由工具生成。
//?????運行庫版本:2.0.50727.1433
//
//?????對此文件的更改可能會導致不正確的行為,并且如果
//?????重新生成代碼,這些更改將會丟失。
//?</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);
????}
}
把這個代理類考到客戶端程序就可以對WCF進行調用了,這里建議大家用工具生成,自己手寫可能會出現錯誤,生成后如果做稍許的改動,都可能造成錯誤,影響到信道數據的傳輸。(但是這里說明一下:這個工具在xp下使用沒問題,但是在2003下使用會有問題,不知是不是我2003統的問題)
停在這里就不動了,不知為啥。
大家這里可能會想到用代碼生成代理類的方法,但是我試了幾次沒有成功,文件生成了但是沒有內容。不知道為什么。高手指點。
有了這個代理類,工作就好做啦!通過這個代理類就可以調用WCF了。


private?void?CreateClientInstanceByProxy(Binding?bind,?EndpointAddress?address,?string?a,?string?b)
{
?????ISrchLib?ws?=?new?SrchLibClient(bind,?address);//傳入binding和服務的URI
?????Repeater1.DataSource?=?ws.SelNoteBySql(a,?b);//a,b是服務中方法的參數
?????Repeater1.DataBind();
???????????
}
這樣,如果多個服務的方法相同,只是address不同(分布在不同的服務器)。這樣的調用是很不錯的選擇!
除此之外,我們可以采用通道工廠的方式生成客戶端服務對象實例,但是前提還是需要上面生成的代理類的幫助。大家可以參看大牛Robin的文章(下面有鏈接)。
ASP.NET AJAX調用WCF
利用ASP.NET AJAX調用WCF:
我們新建網站一個工程,在其添加啟用了Ajax的WCF服務。這樣配置文件中會自動的為我們添加關鍵的節點。
服務中我只是簡單的聲明了一個方法:


public?class?ajaxService
{
????//?添加?[WebGet]?屬性以使用?HTTP?GET
????[OperationContract]
????public?void?DoWork()
????{
????????return;
????}
????[OperationContract]
????public?string?SayHello(string?name)
????{
????????return?"hello:"+name;
????}
????//?在此處添加更多操作并使用?[OperationContract]?標記它們
}
在瀏覽器中預覽我們的服務,然后在地址后加上/js。這樣就可以生成用來訪問WCF的js代理。
生成js代碼:
再來看一下前臺頁面中的代碼:


<html?xmlns="http://www.w3.org/1999/xhtml">
<head?runat="server">
????<title>無標題頁</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設定為剛生成的js文件。這樣,腳本中聲明的方法就可以調用WCF的方法了。運行一下:
這樣就實現了ASP.NET AJAX對WCF的調用。
JS(jQuery)調用WCF
這里實現的思想和ASP.NET Ajax的有些類似,只不過有一些工作需要我們自己來完成,并且這個方法很靈活。
首先是WCF上:我們要在類和方法前進行如下的聲明:


[ServiceContract(Namespace?=?"")]
????[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;
????????}
????}
接著就是配置文件:


<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>
準備工作做好后就可以前臺調用了:


<html?xmlns="http://www.w3.org/1999/xhtml"?>
<head?runat="server">
????<title>wcf</title>
<script?language="javascript"?type="text/javascript"?src="jquery.js"></script>
<script?language="javascript"?type="text/javascript">
function?sayhello(){
????var?name?=?$("#name").val();
????$.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("服務器超時");}
????????}
????});
????}
</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>
這里的一些注意事項大家可以但看dudu的文章(下面有鏈接)。這樣,我們就可以利用jQuery調用wcf了。
小結:以上就是調用WCF的一些方法,希望對大家學習WCF有幫助。也希望大家分享其他調WCF的方法。
參考學習資料:
Robin:http://www.cnblogs.com/jillzhang/archive/2008/07/26/1252171.html
dudu:http://www.cnblogs.com/dudu/archive/2009/07/14/1523082.html
liulun:http://www.cnblogs.com/liulun/articles/1425382.html