WCF浅尝

1.首先先建立一个WCF服务应用程序

2.再建立一个宿主程序,这里用控制台,添加服务引用,这里会报错:

点击页面确定,回到添加服务页面

点击箭头有如下内容:

这里告诉我们问题的所在,我们只要重新生成解决方案就行了。

好,重新生成解决方案,ok,问题解决,添加引用服务成功。

 3.在控制台程序里启动服务:

 static void Main(string[] args)
        {
            using (ServiceHost host = new ServiceHost(typeof(WcfService2.Service1)))
            {
                host.Opened += (a, b) => { Console.WriteLine("service is opened"); };
                host.Open();
                Console.Read();
} }

这里先把控制台程序设为启动项目

4.运行程序,报错:“服务“WcfService1.Service1”有零个应用程序(非基础结构)终结点。这可能是因为未找到应用程序的配置文件,或者在配置文件中未找到与服务名称匹配的服务元素,或者服务元素中未定义终结点”。

这个问题是宿主的配置文件出现问题,如果宿主是控制台,请修改app.config 配置:代码如下

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <system.serviceModel>
    <services>
      <service name="WcfService2.Service1" behaviorConfiguration="MessageBehavior" >
        <host>
          <baseAddresses >
            <add baseAddress="http://localhost:13563/WcfService2"/>
          </baseAddresses>
        </host>
        <endpoint address="" binding="wsHttpBinding" contract="WcfService2.IService1"></endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="MessageBehavior">
          <!-- 为避免泄漏元数据信息,请在部署前将以下值设置为 false -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- 要接收故障异常详细信息以进行调试,请将以下值设置为 true。在部署前设置为 false 以避免泄漏异常信息 -->
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

5.好问题解决,但是又出现新的问题:HTTP 无法注册 URL http://+:13563/WcfService2/。进程不具有此命名空间的访问权限(有关详细信息,请参见 http://go.microsoft.com/fwlink/?LinkId=70353)。

这个问题主要是win7或者win8系统权限问题,点击vs启动程序,右键点“以管理员身份”运行程序即可解决

6.关闭VS2010,以管理员身份运行

好,终于成功了

7.调用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;

namespace WcfService1
{
    class Program
    {
        static void Main(string[] args)
        {
            ConsoleApplication1.ServiceReference1.Service1Client wcfClient = new ConsoleApplication1.ServiceReference1.Service1Client();

            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();

            watch.Start();
            Console.WriteLine(  wcfClient.GetData(10));

            watch.Stop();
            Console.WriteLine("耗时:" + watch.ElapsedMilliseconds);
            Console.ReadKey();
        }
    }
}

结果:

 终于成功了,我因为是初学,所有才会出现这么多问题,希望能帮到和我一样的初学者,如果那个高手有简便后者快捷的方法,可以告诉我,我这方法太笨了。期待你的指点。

posted @ 2013-05-07 11:01  幕三少  阅读(2502)  评论(9编辑  收藏  举报