我们创建了WCF服务以后,可以通过客户端代理文件在客户端方便的使用WCF服务中定义的方法。要创建客户端代理文件可以通过两种方式:
一、.net中提供的Svcutil.exe工具来进行。这个工具在Program Files\Microsoft SDKs\Windows\v6.0\Bin中,当然了,这个目录要在安装了.net 3.0开发包之后才会有。
生成客户端代理文件之前要先把WCF服务启动起来,然后运行svcutil.exe http://localhost:8080/calc?wsdl。这里假设服务端的URL为http://localhost:8080/calc。执行完上面的命令之后会生成两个文件:一个cs文件,一个output.config文件。
在使用生成的客户端代理文件时,要注意应该把output.config文件改名为app.config,然后把生成的文件添加到客户端项目中,就可以使用了。
二、启动服务以后,在客户端项目上右击,选择Add Service Reference,然后添上服务的地址和Service Reference Name。.net会自动生成配置文件和客户端代理文件。

另外,在编写服务器端配置文件时,记得添加 serviceMetadata Behaviors,否则我们无法使用 Svcutil.exe 或 VS2005 创建客户端代理文件。
如果不使用配置文件,则需要把serviceMetadata Behaviors添加到ServiceHost中。以下是个例子:
public static void StartServer()
{
    Console.WriteLine(
"Server is starting...");

    
//ServiceHost host = new ServiceHost(typeof(CalculateService1));
    host = new ServiceHost(typeof(CalculateService1), new Uri("http://localhost:8080/calc"));
    host.AddServiceEndpoint(
typeof(ICalculate1), new BasicHttpBinding(), "http://localhost:8080/calc");

    ServiceMetadataBehavior behavior 
= new ServiceMetadataBehavior();
    behavior.HttpGetEnabled 
= true;
    behavior.HttpGetUrl 
= new Uri("http://localhost:8080/calc");
    host.Description.Behaviors.Add(behavior);

    host.Open();

    Console.WriteLine(
"Server has started.");
}
posted on 2007-12-25 14:51  pdfw  阅读(1341)  评论(1编辑  收藏  举报