Learn WCF (6)--学习调用WCF服务的各种方法
开发工具调用WCF
这中方法很方便也很简单,很多工作VS就帮我们完成了。相信大家也不会对这种方法陌生。这里简单提一下。打开VS,在项目中添加服务引用:
在config中自动声明了有关服务的节点信息,这样VS就创建了调用服务的代理:
poxy.服务中相应的方法。
C#动态调用WCF
这个方法比较实用,可以通过工具或代码生成代理类Proxy.cs,来和WCF进行交互。不需要人为的手动进行服务的引用。生成代理类,这里我里用了工具:SvcUtil.exe,没有的朋友可以下载:SvcUtil.rar
使用方法很简单,只需将SvcUtil.exe随便放置一个位置(这里放在C:/新建文件夹)。在命令提示行中输入如下指令:
这里要注意的是SvcUtil.exe后面是服务的地址,会在工具所在的目录下生成代理类文件:
工具会给我们生成一个代理类文件,代码如下:
<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->//------------------------------------------------------------------------------
//<auto-generated>
//此代码由工具生成。
//运行库版本:2.0.50727.1433
//
//对此文件的更改可能会导致不正确的行为,并且如果
//重新生成代码,这些更改将会丢失。
//</auto-generated>
//------------------------------------------------------------------------------
namespaceLtraSrchLib.DAL
{
usingSystem.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")]
publicpartialclassDbModal:object,System.Runtime.Serialization.IExtensibleDataObject
{
privateSystem.Runtime.Serialization.ExtensionDataObjectextensionDataField;
privatestringArtReferenceField;
privatestringArticalLevelField;
privatestringChineseAbstractField;
privatestringChineseKeywordField;
privatestringChineseTitleField;
privatestringDownLoadPathField;
privatestringEnglishAbstractField;
privatestringEnglishKeywordField;
privatestringEnglishTitleField;
privatestringFileClassField;
privatestringIdField;
privatestringPageNumField;
privatestringPublishedDateField;
privatestringSchoolField;
privatestringSpecialtyField;
privatestringStateField;
privatestringStudentNameField;
privatestringStudentNumField;
privatestringStudyToField;
privatestringTeacherField;
privatestringUpLoadDateField;
publicSystem.Runtime.Serialization.ExtensionDataObjectExtensionData
{
get
{
returnthis.extensionDataField;
}
set
{
this.extensionDataField=value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
publicstringArtReference
{
get
{
returnthis.ArtReferenceField;
}
set
{
this.ArtReferenceField=value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
publicstringArticalLevel
{
get
{
returnthis.ArticalLevelField;
}
set
{
this.ArticalLevelField=value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
publicstringChineseAbstract
{
get
{
returnthis.ChineseAbstractField;
}
set
{
this.ChineseAbstractField=value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
publicstringChineseKeyword
{
get
{
returnthis.ChineseKeywordField;
}
set
{
this.ChineseKeywordField=value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
publicstringChineseTitle
{
get
{
returnthis.ChineseTitleField;
}
set
{
this.ChineseTitleField=value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
publicstringDownLoadPath
{
get
{
returnthis.DownLoadPathField;
}
set
{
this.DownLoadPathField=value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
publicstringEnglishAbstract
{
get
{
returnthis.EnglishAbstractField;
}
set
{
this.EnglishAbstractField=value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
publicstringEnglishKeyword
{
get
{
returnthis.EnglishKeywordField;
}
set
{
this.EnglishKeywordField=value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
publicstringEnglishTitle
{
get
{
returnthis.EnglishTitleField;
}
set
{
this.EnglishTitleField=value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
publicstringFileClass
{
get
{
returnthis.FileClassField;
}
set
{
this.FileClassField=value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
publicstringId
{
get
{
returnthis.IdField;
}
set
{
this.IdField=value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
publicstringPageNum
{
get
{
returnthis.PageNumField;
}
set
{
this.PageNumField=value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
publicstringPublishedDate
{
get
{
returnthis.PublishedDateField;
}
set
{
this.PublishedDateField=value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
publicstringSchool
{
get
{
returnthis.SchoolField;
}
set
{
this.SchoolField=value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
publicstringSpecialty
{
get
{
returnthis.SpecialtyField;
}
set
{
this.SpecialtyField=value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
publicstringState
{
get
{
returnthis.StateField;
}
set
{
this.StateField=value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
publicstringStudentName
{
get
{
returnthis.StudentNameField;
}
set
{
this.StudentNameField=value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
publicstringStudentNum
{
get
{
returnthis.StudentNumField;
}
set
{
this.StudentNumField=value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
publicstringStudyTo
{
get
{
returnthis.StudyToField;
}
set
{
this.StudyToField=value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
publicstringTeacher
{
get
{
returnthis.TeacherField;
}
set
{
this.TeacherField=value;
}
}
[System.Runtime.Serialization.DataMemberAttribute()]
publicstringUpLoadDate
{
get
{
returnthis.UpLoadDateField;
}
set
{
this.UpLoadDateField=value;
}
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel","3.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(ConfigurationName="ISrchLib")]
publicinterfaceISrchLib
{
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/ISrchLib/SelNoteBySql",ReplyAction="http://tempuri.org/ISrchLib/SelNoteBySqlResponse")]
LtraSrchLib.DAL.DbModal[]SelNoteBySql(stringServiceName,stringInfoStr);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel","3.0.0.0")]
publicinterfaceISrchLibChannel:ISrchLib,System.ServiceModel.IClientChannel
{
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel","3.0.0.0")]
publicpartialclassSrchLibClient:System.ServiceModel.ClientBase<ISrchLib>,ISrchLib
{
publicSrchLibClient()
{
}
publicSrchLibClient(stringendpointConfigurationName):
base(endpointConfigurationName)
{
}
publicSrchLibClient(stringendpointConfigurationName,stringremoteAddress):
base(endpointConfigurationName,remoteAddress)
{
}
publicSrchLibClient(stringendpointConfigurationName,System.ServiceModel.EndpointAddressremoteAddress):
base(endpointConfigurationName,remoteAddress)
{
}
publicSrchLibClient(System.ServiceModel.Channels.Bindingbinding,System.ServiceModel.EndpointAddressremoteAddress):
base(binding,remoteAddress)
{
}
publicLtraSrchLib.DAL.DbModal[]SelNoteBySql(stringServiceName,stringInfoStr)
{
returnbase.Channel.SelNoteBySql(ServiceName,InfoStr);
}
}
把这个代理类考到客户端程序就可以对WCF进行调用了,这里建议大家用工具生成,自己手写可能会出现错误,生成后如果做稍许的改动,都可能造成错误,影响到信道数据的传输。(但是这里说明一下:这个工具在xp下使用没问题,但是在2003下使用会有问题,不知是不是我2003统的问题)
停在这里就不动了,不知为啥。
大家这里可能会想到用代码生成代理类的方法,但是我试了几次没有成功,文件生成了但是没有内容。不知道为什么。高手指点。
有了这个代理类,工作就好做啦!通过这个代理类就可以调用WCF了。
<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->privatevoidCreateClientInstanceByProxy(Bindingbind,EndpointAddressaddress,stringa,stringb)
{
ISrchLibws=newSrchLibClient(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服务。这样配置文件中会自动的为我们添加关键的节点。
服务中我只是简单的声明了一个方法:
<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> -->publicclassajaxService
{
//添加[WebGet]属性以使用HTTPGET
[OperationContract]
publicvoidDoWork()
{
return;
}
[OperationContract]
publicstringSayHello(stringname)
{
return"hello:"+name;
}
//在此处添加更多操作并使用[OperationContract]标记它们
}
在浏览器中预览我们的服务,然后在地址后加上/js。这样就可以生成用来访问WCF的js代理。
生成js代码:
再来看一下前台页面中的代码:
<!--<br /> <br /> Code highlighting produced by Actipro CodeHighlighter (freeware)<br /> http://www.CodeHighlighter.com/<br /> <br /> --><htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
<title>无标题页</title>
<scripttype="text/javascript">
functionsayhello()
{
varname=$get("txtname").value;
ajaxService.SayHello(name,onSuccess,onFailed);
}
functiononSuccess(res)
{
alert(res);
}
functiononFailed(res)
{
alert(res);
}
</script>
</head>
<body>
<formid="form1"runat="server">
<div>
<asp:ScriptManagerID="ScriptManager1"runat="server">
<Scripts>
<asp:ScriptReferencePath="~/js/ajaxwcf.js"/>
</Scripts>
</asp:ScriptManager>
</div>
<div>
<p>name:<inputid="txtname"type="text"/></p>
<p><inputid="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上:我们要在类和方法前进行如下的声明:
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->[ServiceContract(Namespace="")]
[AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
publicclassWCFservice
{
[OperationContract]
[WebInvoke(RequestFormat=WebMessageFormat.Json,ResponseFormat=WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.WrappedRequest)]
publicstringSayHello(stringname)
{
return"hello:"+name;
}
}
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--><system.serviceModel>
<behaviors>
<endpointBehaviors>
<behaviorname="AllenBehavior">
<enableWebScript/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironmentaspNetCompatibilityEnabled="true"/>
<services>
<servicename="jqueryWCF.WCFservice">
<endpointaddress=""behaviorConfiguration="AllenBehavior"binding="webHttpBinding"contract="jqueryWCF.WCFservice"/>
</service>
</services>
</system.serviceModel>
准备工作做好后就可以前台调用了:
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--><htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
<title>wcf</title>
<scriptlanguage="javascript"type="text/javascript"src="jquery.js"></script>
<scriptlanguage="javascript"type="text/javascript">
functionsayhello(){
varname=$("#name").val();
$.ajax({
type:'post',
url:'/WCFservice.svc/SayHello',
contentType:'text/json',
data:'{"name":"'+name+'"}',
success:function(msg){
vara=eval('('+msg+')');
if(String(a.d).length>0){alert(a.d);}
else{alert("服务器超时");}
}
});
}
</script>
<styletype="text/css">
#content{height:181px;width:549px;}
#title{width:544px;}
</style>
</head>
<body>
<formid="form1"runat="server">
<div>
name:<inputtype="text"id="name"/>
<br/>
<inputtype="button"value="hello"onclick="sayhello();"/>
</div>
</form>
</body>
</html>
小结:以上就是调用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