学习 WCF (6)--学习调用WCF服务的各种方法
开发工具调用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>
准备工作做好后就可以前台调用了:
<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>
小结:以上就是调用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