WCF服务寄宿及调用

以下都采用VS2013,且创建的项目的名称和生成代码都不做修改

一、新建一个WCF服务库项目WcfServiceLibrary1

注:

 1、WCF服务应用程序项目和WCF服务库项目的区别

        ->WCF服务应用程序在VS2013中可以直接运行,类似WebService,可以部署到IIS;

二、创建一个WPF应用程序项目WpfApplication1,用作WCF服务的宿主

1、添加对WcfServiceLibrary1项目的引用;

2、添加对程序集System.ServiceModel的引用

    ->添加引用-》程序集-》System.ServiceModel;

3、在MainWindow.xaml.cs中添加如下引用:

using System.ServiceModel;   
using WcfServiceLibrary1;  

4、添加一个按钮(btnTest)和一个文本框(txtTest);

5、双击按钮添加按钮事件,并添加如下代码:

<span style="white-space:pre">	</span>private void btnTest_Click(object sender, RoutedEventArgs e)
        {
            ServiceHost host = new ServiceHost(typeof(WcfServiceLibrary1.Service1));
            if (host.State != CommunicationState.Opened)
            {
                host.Open();
            }
            if (host.BaseAddresses.Count <= 0)
                return;
            List<Uri> uriList = host.BaseAddresses.ToList<Uri>();
            txtTest.Text = uriList[0].ToString();
        }

6、在App.config中添加如下配置:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
    </startup>
  <system.serviceModel>
    <services>
      <service name="WcfServiceLibrary1.Service1">
        <endpoint address="" binding="basicHttpBinding"
            bindingConfiguration="" contract="WcfServiceLibrary1.IService1" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:6868/wcf1"/>
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="True" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

注:用工具-》WCF服务配置编辑器,没有找到生成baseAddresses、serviceMetadata节点的方法。

三、重新生成解决方案,双击启动WpfApplication1.exe,点击按钮,结果如下图:


四、创建一个WPF应用程序项目WpfApplication2,当作客户端调用WCF服务

1、添加WcfServiceLibrary1项目的引用;

2、添加服务引用,输入http://localhost:6868/wcf1?wsdl并转到,点确定,如下图:


3、在MainWindow.xaml.cs中添加如下引用:

using WcfServiceLibrary1;
using WpfApplication2.ServiceReference1;

4、添加一个按钮(btnTest)和一个文本框(txtTest),并添加如下事件:

<span style="white-space:pre">	</span>private void btnTest_Click(object sender, RoutedEventArgs e)
        {
            Service1Client client = new Service1Client();
            txtTest.Text = client.GetData(12);
        }

五、双击启动WpfApplication2.exe,点击按钮,结果如下:

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值