学习 WCF (6)--学习调用WCF服务的各种方法
根据不同的情况,我们可以用不同的方法调用WCF服务,本文简单总结了一下调用WCF的一些方法(代理类,Ajax...),分享给大家。开发工具调用WCF
这中方法很方便也很简单,很多工作VS就帮我们完成了。相信大家也不会对这种方法陌生。这里简单提一下。打开VS,在项目中添加服务引用:
在config中自动声明了有关服务的节点信息,这样VS就创建了调用服务的代理:
poxy.服务中相应的方法。
C#动态调用WCF
这个方法比较实用,可以通过工具或代码生成代理类Proxy.cs,来和WCF进行交互。不需要人为的手动进行服务的引用。生成代理类,这里我里用了工具:SvcUtil.exe,没有的朋友可以下载:SvcUtil.rar
使用方法很简单,只需将SvcUtil.exe随便放置一个位置(这里放在C:/新建文件夹)。在命令提示行中输入如下指令:
这里要注意的是SvcUtil.exe后面是服务的地址,会在工具所在的目录下生成代理类文件:
工具会给我们生成一个代理类文件,代码如下:
Code//------------------------------------------------------------------------------// <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了。
Codeprivate 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服务。这样配置文件中会自动的为我们添加关键的节点。
服务中我只是简单的声明了一个方法:
Codepublic class ajaxService
{// 添加 [WebGet] 属性以使用 HTTP GET [OperationContract]public void DoWork()
{return;
}
[OperationContract]public string SayHello(string name)
{return "hello:"+name;
}// 在此处添加更多操作并使用 [OperationContract] 标记它们}
在浏览器中预览我们的服务,然后在地址后加上/js。这样就可以生成用来访问WCF的js代理。
生成js代码:
再来看一下前台页面中的代码:
Code<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上:我们要在类和方法前进行如下的声明:
Code[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;
}
}
接着就是配置文件:
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>
准备工作做好后就可以前台调用了:
Code<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.htmlliulun:http://www.cnblogs.com/liulun/articles/1425382.html
学习 WCF (6)--学习调用WCF服务的各种方法相关推荐
- 绑定服务调用本地服务中的方法
如果想调用服务中的方法, 通过startService()是做不到的, 这时需要用bindService来解决. 下面的demo是在Activity中调用Service中的自定义方法---method ...
- httpclient依赖_.NetCore 3.1高性能微服务架构:封装调用外部服务的接口方法HttpClient客户端思路分析...
护士节快乐 众所周知,微服务架构是由一众微服务组成,项目中调用其他微服务接口更是常见的操作.为了便于调用外部接口,我们的常用思路一般都是封装一个外部接口的客户端,使用时候直接调用相应的方法.webse ...
- java cxf 调用wcf接口_JAVA 调用 WCF 服务流程
1. 将 WCF 服务发布到 Windows 服务(或者 IIS) 此步骤的目的是为 WCF 服务搭建服务器,从而使服务相关的 Web Services 可以被 JAVA 客户端程序调用,具体步骤参 ...
- 学习笔记---Web服务、Remoting、WCF (上) --- Web服务
自从程序设计诞生起, 如何最大限度的重用代码, 减小编码的重复劳动就是程序员永恒不变的课题. 我们从学习面向对象开始, 先后引入了很多种共享代码的手段, 随着学习的不断深入就越发觉得程序设计的发展过程 ...
- 前端MVC学习总结(三)——AngularJS服务、路由、内置API、jQueryLite
一.服务 AngularJS功能最基本的组件之一是服务(Service).服务为你的应用提供基于任务的功能.服务可以被视为重复使用的执行一个或多个相关任务的代码块. AngularJS服务是单例对象, ...
- SpringCoud - 基础入门(服务注册与发现、服务调用、服务降级与熔断篇)
SpringCloud:是一系列框架的有序集合,也是一套完整的微服务解决方案.利用SpringBoot的开发便利巧妙的简化了分布式系统基础设施的开发,如发现注册.配置中心.消息总线.负载均衡.断路器. ...
- Dynamic CRM 2013学习笔记(二十二)插件里调用WCF服务
1. 添加service: 2.调用WCF BasicHttpBinding myBinding = new BasicHttpBinding(); myBinding.Name = "Ba ...
- 学习 WCF (5)--学习Binding的使用
网络通信离不开网络协议的支持,在WCF中,给发开人员提供了很多传输协议进行绑定.比如:BasicHttpBinding,NetTcpBinding,WSHttpBinding 等等.对于初学者来说,很 ...
- java调用wcf_详解JAVA调用WCF服务的示例代码
这一篇将要解决java中调用WCF的问题,使用的依旧是上一篇中托管在IIS中的WCF服务,本来我是打算用axis来写这篇文章的,可就在我开始之前,无意中发现了在java包中自带的wsimport工具 ...
最新文章
- 帅气逼人的Redis可视化工具
- sql语句查询性能的优化思想(个人理解)
- 安装php5、卸载php、安装php7的教程
- mysql需要下载调试_Mysql安装和调试
- VTK:Utilities之PCAStatistics
- jpa 去重_spring boot jpa 表关联查询分组 group by 去重
- Linux 的命令终端(CMD)的快捷键(Keyboard of MacBook)
- UI组件-UIPickerView
- 在Intellij idea中快速重写父类方法
- 圆柱体积怎么算立方公式_祖暅原理和球的体积公式
- Zookeeper Java客户端搭建
- html 倒计时弹出框,alert警告框倒计时
- while用法小简介(涉及EOF用法)
- 科技创新就要高浓度、高密度
- 从零开始自制实现WebServer(十二)---- 剑指定时器小根堆处理 给EventLoop定时任务处理一个温暖的家
- hourglass论文_人体姿态估计论文笔记-Hourglass
- MySQL创建S,P,J,SPJ表,以及SQL语句
- (Scikit-Learn)线性回归 基函数的含义详解
- python 日志输出为json格式文件_Py修行路 python基础 (二十一)logging日志模块 json序列化 正则表达式(re)...
- 尚硅谷Vue3(天禹老师主讲)的笔记
热门文章
- QT的QAlphaCoverage类的使用
- 经典C语言程序100例之七六
- python基于web可视化_Python Selenium实现无可视化界面
- 1、虚拟机内存管理、运行时数据区、线程共享区、Java堆、新生代、老年代、Eden区域分配、方法区、线程独占区、虚拟机栈
- MyEclipse9安装Checkstyle5.5插件(图解)
- maven+springMVC+mybatis+junit详细搭建过程
- 01_GIT基础、安装
- 2.Maven特点,Maven约定,建立第一个Maven项目
- windows下安装Oracle10G
- Linux下C编程入门(.h文件,.c文件,以及多文件调用的方式)