练习 配置WCF服务

Posted 260250932

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了练习 配置WCF服务相关的知识,希望对你有一定的参考价值。

 
 

技术分享图1

 

1,OrderTrack.Windows.KZT  : 控制台应用 程序,用于调试 wcf服务端 接口问题,

2,OrderTrack.Windows.Service :  windows服务,可以发布到服务端,

怎么创建 windows 服务 ,可以参考   链接地址  wcf服务注册windows服务

3,FluentAdo.SqlServer   数据源适合wcf服务的那种调用方式,跟常用的调用sqlhelp 有很大区别。

4,WcfWebApplication   展示 客户端调用,

5,其它的 类库 分别 是  接口,实现,实体。

 

1,展示下 控制台应用程序配置

 

web.config配置

 

  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <configuration>  
  3.   <configSections>  
  4.   </configSections>  
  5.   <appSettings>  
  6.     <add key="Travel"  value="Data Source=服务器名;Initial Catalog=xxx;User ID=帐号;Password=密码;Asynchronous Processing=True;MultipleActiveResultSets=True"/>  
  7.     <add key="OrderTrackRouter"  value="Data Source=服务器名;Initial Catalog=数据库名;User ID=帐号;Password=密码"/>  
  8.   </appSettings>  
  9.   <connectionStrings>  
  10.   </connectionStrings>  
  11.   <system.serviceModel>  
  12.     <behaviors>  
  13.       <serviceBehaviors>  
  14.         <behavior name="Wcf.MyBehaviorConfiguration">  
  15.           <serviceMetadata httpGetEnabled="false" />  
  16.           <serviceDebug includeExceptionDetailInFaults="false" />  
  17.           <dataContractSerializer maxItemsInObjectGraph="2147483647" />  
  18.         </behavior>  
  19.       </serviceBehaviors>  
  20.     </behaviors>  
  21.     <bindings>  
  22.         
  23.       <!-- wcf协议 -->  
  24.       <netTcpBinding>  
  25.         <binding name="netTcpBinding_Mybinding"  
  26.                    closeTimeout="00:10:00"  
  27.                    openTimeout="00:10:00"  
  28.                    receiveTimeout="00:10:00"  
  29.                    sendTimeout="00:10:00"  
  30.                    transactionFlow="false"  
  31.                    transferMode="Buffered"  
  32.                    transactionProtocol="OleTransactions"  
  33.                    hostNameComparisonMode="StrongWildcard"  
  34.                    listenBacklog="10"  
  35.                    maxBufferPoolSize="2147483647 "  
  36.                    maxBufferSize="2147483647 "  
  37.                    maxConnections="10"  
  38.                    maxReceivedMessageSize="2147483647 ">  
  39.           <readerQuotas maxDepth="64" maxStringContentLength="2147483647 " maxArrayLength="2147483647 " maxBytesPerRead="4096" maxNameTableCharCount="16384" />  
  40.           <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" />  
  41.           <security mode="None"></security>  
  42.         </binding>  
  43.       </netTcpBinding>  
  44.     </bindings>  
  45.   
  46.     <services>  
  47.       <!--订单跟踪 -->  
  48.       <service name="OrderTrack.DAL.OrderTrackRouter_Service">  
  49.         <endpoint  address="net.tcp://127.0.0.1:6438/OrderTrack.DAL.OrderTrackRouter_Service"  
  50.                    contract="OrderTrack.Interface.OrderTrackRouter_IService"  
  51.                                                         
  52.                     binding="netTcpBinding" bindingConfiguration="netTcpBinding_Mybinding"  />  
  53.       </service>  
  54.         
  55.       <!-- RTX跟踪 -->  
  56.       <service name="OrderTrack.DAL.RTXhistoryDAL">  
  57.         <endpoint  address="net.tcp://127.0.0.1:5789/OrderTrack.DAL.RTXhistoryDAL"  
  58.                   contract="OrderTrack.Interface.IRTXhistoryDAL"  
  59.                     binding="netTcpBinding" bindingConfiguration="netTcpBinding_Mybinding"  />  
  60.       </service>  
  61.     </services>  
  62.   
  63.   
  64.     <client>  
  65.   
  66.   
  67.   </system.serviceModel>  
  68. </configuration>  
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
  </configSections>
  <appSettings>
    <add key="Travel"  value="Data Source=服务器名;Initial Catalog=xxx;User ID=帐号;Password=密码;Asynchronous Processing=True;MultipleActiveResultSets=True"/>
    <add key="OrderTrackRouter"  value="Data Source=服务器名;Initial Catalog=数据库名;User ID=帐号;Password=密码"/>
  </appSettings>
  <connectionStrings>
  </connectionStrings>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="Wcf.MyBehaviorConfiguration">
          <serviceMetadata httpGetEnabled="false" />
          <serviceDebug includeExceptionDetailInFaults="false" />
          <dataContractSerializer maxItemsInObjectGraph="2147483647" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <bindings>
      
      <!-- wcf协议 -->
      <netTcpBinding>
        <binding name="netTcpBinding_Mybinding"
                   closeTimeout="00:10:00"
                   openTimeout="00:10:00"
                   receiveTimeout="00:10:00"
                   sendTimeout="00:10:00"
                   transactionFlow="false"
                   transferMode="Buffered"
                   transactionProtocol="OleTransactions"
                   hostNameComparisonMode="StrongWildcard"
                   listenBacklog="10"
                   maxBufferPoolSize="2147483647 "
                   maxBufferSize="2147483647 "
                   maxConnections="10"
                   maxReceivedMessageSize="2147483647 ">
          <readerQuotas maxDepth="64" maxStringContentLength="2147483647 " maxArrayLength="2147483647 " maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" />
          <security mode="None"></security>
        </binding>
      </netTcpBinding>
    </bindings>

    <services>
      <!--订单跟踪 -->
      <service name="OrderTrack.DAL.OrderTrackRouter_Service">
        <endpoint  address="net.tcp://127.0.0.1:6438/OrderTrack.DAL.OrderTrackRouter_Service"
                   contract="OrderTrack.Interface.OrderTrackRouter_IService"
                                                      
                    binding="netTcpBinding" bindingConfiguration="netTcpBinding_Mybinding"  />
      </service>
      
      <!-- RTX跟踪 -->
      <service name="OrderTrack.DAL.RTXhistoryDAL">
        <endpoint  address="net.tcp://127.0.0.1:5789/OrderTrack.DAL.RTXhistoryDAL"
                  contract="OrderTrack.Interface.IRTXhistoryDAL"
                    binding="netTcpBinding" bindingConfiguration="netTcpBinding_Mybinding"  />
      </service>
    </services>


    <client>


  </system.serviceModel>
</configuration>

注意事项:  1,wcf协议可以共用一个

                2,tcp服务端口部署到服务器,端口号不能重复重复之后,windows服务启动不了,会产生错误日志。出现服务启用不了,

                    修改 端口号,除了这个原因,还有别的原因也会导致服务启动不了。可以到事件查看器 查看对应错误,如:图2

技术分享

  右键点击错误日志属性查看错误

 

 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.ServiceModel;  
  6. using OrderTrack.DAL;  
  7.   
  8. /* 
  9.     创建人 谈勇 2012-11-7 
  10.  */  
  11. namespace OrderTrack.Windows.Service.WCFService  
  12. {  
  13.     internal class RtxStartService  
  14.     {  
  15.         /// <summary>  
  16.         /// 创建服务主机对象  
  17.         /// </summary>  
  18.         internal static ServiceHost serviceHost = null;  
  19.   
  20.   
  21.         /// <summary>  
  22.         /// 启动服务函数  
  23.         /// </summary>  
  24.         internal static void StartService()  
  25.         {  
  26.             if (serviceHost != null)  
  27.             {  
  28.                 serviceHost.Close();  
  29.             }  
  30.             serviceHost = new ServiceHost(typeof(RTXhistoryDAL));  
  31.             serviceHost.Open();  
  32.         }  
  33.   
  34.         /// <summary>  
  35.         /// 停止服务  
  36.         /// </summary>  
  37.         internal static void StopService()  
  38.         {  
  39.             if (serviceHost != null)  
  40.             {  
  41.                 serviceHost.Close();  
  42.                 serviceHost = null;  
  43.             }  
  44.         }  
  45.     }  
  46. }  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using OrderTrack.DAL;

/*
    创建人 谈勇 2012-11-7
 */
namespace OrderTrack.Windows.Service.WCFService
{
    internal class RtxStartService
    {
        /// <summary>
        /// 创建服务主机对象
        /// </summary>
        internal static ServiceHost serviceHost = null;


        /// <summary>
        /// 启动服务函数
        /// </summary>
        internal static void StartService()
        {
            if (serviceHost != null)
            {
                serviceHost.Close();
            }
            serviceHost = new ServiceHost(typeof(RTXhistoryDAL));
            serviceHost.Open();
        }

        /// <summary>
        /// 停止服务
        /// </summary>
        internal static void StopService()
        {
            if (serviceHost != null)
            {
                serviceHost.Close();
                serviceHost = null;
            }
        }
    }
}
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Diagnostics;  
  6. using System.Linq;  
  7. using System.ServiceProcess;  
  8. using System.Text;  
  9. using OrderTrack.Windows.KZT.WCFService;  
  10.   
  11. namespace OrderTrack.Windows.KZT  
  12. {  
  13.     partial class WindowsService : ServiceBase  
  14.     {  
  15.         /// <summary>  
  16.         /// 服务名称  
  17.         /// </summary>  
  18.         internal const string SERVICE_NAME = "WCFServiceHost";  
  19.   
  20.         protected static void WCFServiceHost_Start()  
  21.         {  
  22.             //订单跟踪服务启动  
  23.             OrderTrackRouter_WCFService.StartService();  
  24.             //rtx 服务启动  
  25.             RtxStartService.StartService();  
  26.         }  
  27.   
  28.         protected static void WCFServiceHost_Stop()  
  29.         {  
  30.             //调用服务停止函数  
  31.            // WhetherStartService.StopService();  
  32.             //rtx 服务关闭  
  33.             //RtxStartService.StopService();  
  34.   
  35.         }  
  36.   
  37.         public WindowsService()  
  38.         {  
  39.             //InitializeComponent();  
  40.   
  41.             ServiceName = SERVICE_NAME;  
  42.         }  
  43.   
  44.         protected override void OnStart(string[] args)  
  45.         {  
  46.             // TODO: 在此处添加代码以启动服务。  
  47.             WCFServiceHost_Start();  
  48.         }  
  49.   
  50.         protected override void OnStop()  
  51.         {  
  52.             // TODO: 在此处添加代码以执行停止服务所需的关闭操作。  
  53.             WCFServiceHost_Stop();  
  54.         }  
  55.   
  56.         private static void RunAsConsole()  
  57.         {  
  58.             ///添加控制台TITLE   
  59.             Console.Title = "我的地盘听我的";  
  60.             WCFServiceHost_Start();  
  61.             Console.ReadKey();  //不做控制台程序可以 修改成 Consolse.Read();   
  62.         }  
  63.   
  64.         private static void RunAsService()  
  65.         {  
  66.             //Run(new WindowsService());  
  67.   
  68.             ServiceBase[] ServicesToRun;  
  69.             ServicesToRun = new ServiceBase[]   
  70.             {   
  71.                 new WindowsService()   
  72.             };  
  73.             ServiceBase.Run(ServicesToRun);  
  74.         }  
  75.   
  76.         public static void Main()  
  77.         {  
  78.             if (Environment.UserInteractive)  
  79.             {  
  80.                 RunAsConsole();  
  81.             }  
  82.             else  
  83.             {  
  84.                 RunAsService();  
  85.             }  
  86.   
  87.         }  
  88.     }  
  89. }  
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using OrderTrack.Windows.KZT.WCFService;

namespace OrderTrack.Windows.KZT
{
    partial class WindowsService : ServiceBase
    {
        /// <summary>
        /// 服务名称
        /// </summary>
        internal const string SERVICE_NAME = "WCFServiceHost";

        protected static void WCFServiceHost_Start()
        {
            //订单跟踪服务启动
            OrderTrackRouter_WCFService.StartService();
            //rtx 服务启动
            RtxStartService.StartService();
        }

        protected static void WCFServiceHost_Stop()
        {
            //调用服务停止函数
           // WhetherStartService.StopService();
            //rtx 服务关闭
            //RtxStartService.StopService();

        }

        public WindowsService()
        {
            //InitializeComponent();

            ServiceName = SERVICE_NAME;
        }

        protected override void OnStart(string[] args)
        {
            // TODO: 在此处添加代码以启动服务。
            WCFServiceHost_Start();
        }

        protected override void OnStop()
        {
            // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
            WCFServiceHost_Stop();
        }

        private static void RunAsConsole()
        {
            ///添加控制台TITLE 
            Console.Title = "我的地盘听我的";
            WCFServiceHost_Start();
            Console.ReadKey();  //不做控制台程序可以 修改成 Consolse.Read(); 
        }

        private static void RunAsService()
        {
            //Run(new WindowsService());

            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
			{ 
				new WindowsService() 
			};
            ServiceBase.Run(ServicesToRun);
        }

        public static void Main()
        {
            if (Environment.UserInteractive)
            {
                RunAsConsole();
            }
            else
            {
                RunAsService();
            }

        }
    }
}
技术分享图3, 服务配置

 

 

技术分享图4 ,wcf接口的实现

 

      <!-- RTX跟踪 -->       <service name="OrderTrack.DAL.RTXhistoryDAL">         <endpoint  address="net.tcp://127.0.0.1:5789/OrderTrack.DAL.RTXhistoryDAL"                   contract="OrderTrack.Interface.IRTXhistoryDAL"                     binding="netTcpBinding" bindingConfiguration="netTcpBinding_Mybinding"  />       </service>

  注意看图 4 和 协议的配置 是有关联的。

 

总结一下,wcf配置一定要细心,监听和协议有一点不一样,那个客户端 调用 服务器 接口 是 ping 不通的。

 

5. 展示客户端调用

技术分享

 

要下载个 wcf插件

ACorns.WCF.DynamicClientProxy   文件  可以用一个专门的类型去封装 那个 wcf插件文件包

客户端引用 只要拿 那个 dll文件就行。

 

总结:编写wcf接口服务 调用 设计的越简单越好,这样别人拿到你的接口 ,引用几个 dll文件。就能实现你接口的方法 完成对应功能。

客户端的web配置

  1. <?xml version="1.0"?>  
  2.   
  3. <!--  
  4.   有关如何配置 ASP.NET 应用程序的详细信息,请访问  
  5.   http://go.microsoft.com/fwlink/?LinkId=169433  
  6.   -->  
  7.   
  8. <configuration>  
  9.   <connectionStrings />  
  10.   
  11.   
  12.   <system.web>  
  13.     <compilation debug="true" targetFramework="4.0" />  
  14.   
  15.     <authentication mode="Forms">  
  16.       <forms loginUrl="~/Account/Login.aspx" timeout="2880" />  
  17.     </authentication>  
  18.   
  19.     <membership>  
  20.       <providers>  
  21.         <clear/>  
  22.         <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"  
  23.              enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"  
  24.              maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"  
  25.              applicationName="/" />  
  26.       </providers>  
  27.     </membership>  
  28.   
  29.     <profile>  
  30.       <providers>  
  31.         <clear/>  
  32.         <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>  
  33.       </providers>  
  34.     </profile>  
  35.   
  36.     <roleManager enabled="false">  
  37.       <providers>  
  38.         <clear/>  
  39.         <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />  
  40.         <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />  
  41.       </providers>  
  42.     </roleManager>  
  43.   
  44.   </system.web>  
  45.   
  46.   <system.webServer>  
  47.      <modules runAllManagedModulesForAllRequests="true"/>  
  48.   </system.webServer>  
  49.   
  50.   <!-- wcf 配置 begin-->  
  51.   <system.serviceModel>  
  52.     <bindings>  
  53.       <netTcpBinding>  
  54.         <binding name="netTcpBinding_Mybinding"  
  55.                      closeTimeout="00:10:00"  
  56.                      openTimeout="00:10:00"  
  57.                      receiveTimeout="00:10:00"  
  58.                      sendTimeout="00:10:00"  
  59.                      transactionFlow="false"  
  60.                      transferMode="Buffered"  
  61.                      transactionProtocol="OleTransactions"  
  62.                      hostNameComparisonMode="StrongWildcard"  
  63.                      listenBacklog="10"  
  64.                      maxBufferPoolSize="2147483647 "  
  65.                      maxBufferSize="2147483647 "  
  66.                      maxConnections="10"  
  67.                      maxReceivedMessageSize="2147483647 ">  
  68.           <readerQuotas maxDepth="64" maxStringContentLength="2147483647 " maxArrayLength="2147483647 " maxBytesPerRead="4096" maxNameTableCharCount="16384" />  
  69.           <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false" />  
  70.           <security mode="None"></security>  
  71.         </binding>  
  72.   
  73.       </netTcpBinding>  
  74.     </bindings>  
  75.   
  76.     <client>  
  77.       <!-- 订单跟踪 -->  
  78.       <endpoint  address="net.tcp://127.0.0.1:6438/OrderTrack.DAL.OrderTrackRouter_Service" contract="OrderTrack.Interface.OrderTrackRouter_IService"  
  79.                  binding="netTcpBinding" bindingConfiguration="netTcpBinding_Mybinding" name="orderTrack"/>  
  80.       <!-- RTX跟踪 -->  
  81.       <endpoint  address="net.tcp://127.0.0.1:5789/OrderTrack.DAL.RTXhistoryDAL" contract="OrderTrack.Interface.IRTXhistoryDAL"  
  82.            binding="netTcpBinding" bindingConfiguration="netTcpBinding_Mybinding" name="rtxTrack"/>  
  83.     </client>  
  84.   </system.serviceModel>  
  85.   
  86.   <!-- wcf 配置  end-->  
  87. </configuration>  
<?xml version="1.0"?>

<!--
  有关如何配置 ASP.NET 应用程序的详细信息,请访问
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
  <connectionStrings />


  <system.web>
    <compilation debug="true" targetFramework="4.0" />

    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login.aspx" timeout="2880" />
    </authentication>

    <membership>
      <providers>
        <clear/>
        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
             enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
             maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
             applicationName="/" />
      </providers>
    </membership>

    <profile>
      <providers>
        <clear/>
        <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
      </providers>
    </profile>

    <roleManager enabled="false">
      <providers>
        <clear/>
        <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
        <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
      </providers>
    </roleManager>

  </system.web>

  <system.webServer>
     <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

  <!-- wcf 配置 begin-->
  <system.serviceModel>
    <bindings>
      <netTcpBinding>
        <binding name="netTcpBinding_Mybinding"
                     closeTimeout="00:10:00"
                     openTimeout="00:10:00"
                     receiveTimeout="00:10:00"
                     sendTimeout="00:10:00"
                     transactionFlow="false"
                     transferMode="Buffered"
                     transactionProtocol="OleTransactions"
                     hostNameComparisonMode="StrongWildcard"
                     listenBacklog="10"
                     maxBufferPoolSize="2147483647 "
                     maxBufferSize="2147483647 "
                     maxConnections="10"
                     maxReceivedMessageSize="2147483647 ">
          <readerQuotas maxDepth="64" maxStringContentLengt

以上是关于练习 配置WCF服务的主要内容,如果未能解决你的问题,请参考以下文章

wcf 配置文件与代码配置的优缺点

在 IIS 中托管时如何从代码配置 WCF 服务?

[转]使用代码去描述WCF配置文件

通过C#代码调用WCF服务中的一个方法。不依赖配置文件等。求完整代码!!

使用代码而不是配置文件将消息检查器添加到 WCF 服务

WCF学习之旅—WCF服务配置(十四)