根据不同的情况,我们可以用不同的方法调用WCF服务,本文简单总结了一下调用WCF的一些方法(代理类,Ajax...),分享给大家。开发工具调用WCF
这中方法很方便也很简单,很多工作VS就帮我们完成了。相信大家也不会对这种方法陌生。这里简单提一下。打开VS,在项目中添加服务引用:
![](https://img-blog.csdnimg.cn/img_convert/4be6f5d3771c4bfddb7d02e877875a48.png)
![](https://img-blog.csdnimg.cn/img_convert/86857ba6e93d8c6338659a131de12ad9.png)
在config中自动声明了有关服务的节点信息,这样VS就创建了调用服务的代理:
poxy.服务中相应的方法。
C#动态调用WCF
这个方法比较实用,可以通过工具或代码生成代理类Proxy.cs,来和WCF进行交互。不需要人为的手动进行服务的引用。生成代理类,这里我里用了工具:SvcUtil.exe,没有的朋友可以下载:SvcUtil.rar
使用方法很简单,只需将SvcUtil.exe随便放置一个位置(这里放在C:/新建文件夹)。在命令提示行中输入如下指令:
![](https://img-blog.csdnimg.cn/img_convert/fba389fca543bb84a327f919a48f06a6.png)
这里要注意的是SvcUtil.exe后面是服务的地址,会在工具所在的目录下生成代理类文件:
![](https://img-blog.csdnimg.cn/img_convert/5e1fd45ea7dd6fca809cea35a1fcc926.png)
工具会给我们生成一个代理类文件,代码如下:
![](https://img-blog.csdnimg.cn/img_convert/3037a9f5051ab53f16a01afbac4f892b.gif)
![](https://img-blog.csdnimg.cn/img_convert/7a8da4ac707f61d4b7404a5247cedb30.gif)
{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统的问题)
![](https://img-blog.csdnimg.cn/img_convert/27eb4e74634256d554c676439b03c7a7.png)
停在这里就不动了,不知为啥。
大家这里可能会想到用代码生成代理类的方法,但是我试了几次没有成功,文件生成了但是没有内容。不知道为什么。高手指点。
有了这个代理类,工作就好做啦!通过这个代理类就可以调用WCF了。
![](https://img-blog.csdnimg.cn/img_convert/b55926089bd719999aa99308b39a19cc.gif)
![](https://img-blog.csdnimg.cn/img_convert/18f3d7a3f5b8025792a9607e20191115.gif)
{
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服务。这样配置文件中会自动的为我们添加关键的节点。
![](https://img-blog.csdnimg.cn/img_convert/95526db150289af97128c7e213a16944.png)
服务中我只是简单的声明了一个方法:
![](https://img-blog.csdnimg.cn/img_convert/736f84fa496adf4170bda1b8535bfa8d.gif)
![](https://img-blog.csdnimg.cn/img_convert/0638cf96620c13f7749c30bf0fefed9d.gif)
{// 添加 [WebGet] 属性以使用 HTTP GET [OperationContract]public void DoWork()
{return;
}
[OperationContract]public string SayHello(string name)
{return "hello:"+name;
}// 在此处添加更多操作并使用 [OperationContract] 标记它们}
在浏览器中预览我们的服务,然后在地址后加上/js。这样就可以生成用来访问WCF的js代理。
![](https://img-blog.csdnimg.cn/img_convert/c8278a20f9a747eefa8a4cf6c17b3f8f.png)
![](https://img-blog.csdnimg.cn/img_convert/73de82d2ea4fbda40525e116d7ff32d0.png)
再来看一下 前台页面中的代码:
![](https://img-blog.csdnimg.cn/img_convert/abe7c6aff11ed3fd8678fb7e39b26d06.gif)
![](https://img-blog.csdnimg.cn/img_convert/3c67673d2b5dcfb9b07bb2909975b8df.gif)
{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的方法了。运行一下:
![](https://img-blog.csdnimg.cn/img_convert/8696388cf23c3f0be96537c3b90b4d10.png)
这样就实现了ASP.NET AJAX对WCF的调用。 JS(jQuery)调用WCF
这里实现的思想和ASP.NET Ajax的有些类似,只不过有一些工作需要我们自己来完成,并且这个方法很灵活。
首先是WCF上:我们要在类和方法前进行如下的声明:
![](https://img-blog.csdnimg.cn/img_convert/7d7a7a470933cd6d75ee47d3e70e6158.gif)
![](https://img-blog.csdnimg.cn/img_convert/8512ad072c36756466dd7a311d60b364.gif)
[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;
}
}
接着就是配置文件:
![](https://img-blog.csdnimg.cn/img_convert/e4d8da9e4488fd9ab8fbda3c3fea1901.gif)
![](https://img-blog.csdnimg.cn/img_convert/526dfde8c3c5c4b31332f776e1b52414.gif)
<behavior name="AllenBehavior"><enableWebScript /></behavior>
准备工作做好后就可以前台调用了:
![](https://img-blog.csdnimg.cn/img_convert/937938ebd8c545679004aacc5cd843a2.gif)
![](https://img-blog.csdnimg.cn/img_convert/672beebd4e36f721a14d09bdb966eee8.gif)
$.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了。
![](https://img-blog.csdnimg.cn/img_convert/d9087decd69ff34cb1ddde0b5211d398.png)
小结:以上就是调用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.htmlliulun: http://www.cnblogs.com/liulun/articles/1425382.html