This is the third of six tasks required to create a Windows Communication Foundation (WCF) application. For an overview of all six of the tasks, see the Getting Started Tutorial topic.

This topic describes how to host a Windows Communication Foundation (WCF) service in a console application. This procedure consists of the following steps:

这个主题描述了如何在控制台应用程序中托管一个wcf服务。包含以下几个步骤

  • Create a console application project to host the service.      创建一个控制台应用项目来托管服务

  • Create a service host for the service.    //为服务创建一个servicehost

  • Enable metadata exchange.  启用元数据的交换

  • Open the service host.    打开servicehost

A complete listing of the code written in this task is provided in the example following the procedure.

To create a new console application to host the service

  • 1.Create a new Console Application project by right-clicking on the Getting Started solution, selecting, Add, New Project. In the Add New Project dialog on the left hand side of the dialog select Windows underC# or VB. In the center section of the dialog select Console Application. Name the project GettingStartedHost.

右键解决方案,创建一个新的控制台应用程序。选择添加,新建项目。新建一个名为GettingStartedHost。

  • 2.Set the target framework of the GettingStartedHost project to .NET Framework 4.5 by right clicking on GettingStartedHost in the Solution Explorer and selecting Properties. In the dropdown box labeledTarget Framework select .NET Framework 4.5. Setting the target framework for a VB project is a little different, in the GettingStartedHost project properties dialog, click the Compile tab on the left-hand side of the screen, and then click the Advanced Compile Options button at the lower left-hand corner of the dialog. Then select .NET Framework 4.5 in the dropdown box labeled Target Framework.

Setting the target framework will cause Visual Studio 2012 to reload the solution, press OK when prompted.

右键解决方案资源管理器中GettingStartedHost项目属性,设置项目为.net4.5框架。

  • 3.Add a reference to the GettingStartedLib project to the GettingStartedHost project by right clicking on the References folder under the GettingStartedHost project in the solution explorer and select Add Reference. In the Add Reference dialog, select Solution on the left-hand side of the dialog and select GettingStartedLib in the center section of the dialog and click Add. This makes the types defined in GettingStartedLib available to the GettingStartedHost project.

添加GettingStartedLib 项目作为GettingStartedHost 的引用。

  • 4.Add a reference to System.ServiceModel to the GettingStartedHost project by right-clicking the Reference folder under the GettingStartedHost project in Solution Explorer and select Add Reference. In the Add Reference dialog select Framework on the left-hand side of the dialog. In the Search Assemblies textbox, type in System.ServiceModel. In the center section of the dialog select System.ServiceModel, click theAdd button, and click the Close button. Save the solution by clicking the Save All button below the main menu.

给GettingStartedHost 项目添加System.ServiceModel的引用。

To host the service

  • Open the Program.cs or Module.vb file and enter the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;//Uri和ServiceHost
using System.ServiceModel.Description;//ServiceMetadataBehavior
using GettingStartedLib; namespace GettingStartedHost
{
class Program
{
static void Main(string[] args)
{
// Step 1 Create a URI to serve as the base address.
Uri baseAddress = new Uri("http://localhost:8000/GettingStarted/"); // Step 2 Create a ServiceHost instance
ServiceHost selfHost = new ServiceHost(typeof(CalculatorService), baseAddress); try
{
// Step 3 Add a service endpoint.
selfHost.AddServiceEndpoint(typeof(ICalculator), new WSHttpBinding(), "CalculatorService"); // Step 4 Enable metadata exchange.
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
selfHost.Description.Behaviors.Add(smb); // Step 5 Start the service.
selfHost.Open();
Console.WriteLine("The service is ready.");
Console.WriteLine("Press <ENTER> to terminate service.");
Console.WriteLine();
Console.ReadLine(); // Close the ServiceHostBase to shutdown the service.
selfHost.Close();
}
catch (CommunicationException ce)
{
Console.WriteLine("An exception occurred: {0}", ce.Message);
selfHost.Abort();
}
}
}
}
  • Step 1 - Creates an instance of the Uri class to hold the base address of the service. Services are identified by a URL which contains a base address and an optional URI. The base address is formatted as follows:[transport]://[machine-name or domain][:optional port #]/[optional URI segment]The base address for the calculator service uses the HTTP transport, localhost, port 8000, and the URI segment “GettingStarted”

创建一个Uri类的实例,来保存服务的基础地址。服务通过url来进行识别,url包含了基础地址以及可选的uri。基础地址的格式如下:[transport]://[machine-name or domain][:optional port#]/[optional URI segment]

calculator 服务的基地址,使用的是http传输,localhost,端口8000。URI部分为GettingStarted

  • Step 2 – Creates an instance of the ServicHost class to host the service. The constructor takes two parameters, the type of the class that implements the service contract, and the base address of the service.

创建一个ServicHost 类的实例来托管服务。构造函数接受2个参数,实现了服务契约的类的类型,服务的基地址。

  • Step 3 – Creates a ServiceEndpoint instance. A service endpoint is composed of an address, a binding, and a service contract. The ServiceEndpoint constructor therefore takes the service contract interface type, a binding, and an address. The service contract is ICalculator, which you defined and implement in the service type. The binding used in this sample is WSHttpBinding which is a built-in binding that is used for connecting to endpoints that conform to the WS-* specifications. For more information about WCF bindings, see Windows Communication Foundation Bindings Overview. The address is appended to the base address to identify the endpoint. The address specified in this code is “Calculator” so the fully qualified address for the endpoint is“http://localhost:8000/GettingStartedService/Calculator”

创建ServiceEndpoint 的实例。服务终结点由地址,绑定,服务契约构成。服务终结点的构造函数需要服务契约的接口类型,绑定以及地址。服务契约是ICalculator,此接口定义了,并且在服务类型中实现。在这个示例中使用的绑定是WSHttpBinding,用来连接符合WS-*规范的终结点。地址附加到基地址上来识别终结点。这个代码示例中的地址指定为Calculator,所以这个终结点的完全限定地址为http://localhost:8000/GettingStartedService/Calculator

Important

Adding a service endpoint is optional when using .NET Framework 4 or later. In these versions, if no endpoints are added in code or configuration, WCF adds one default endpoint for each combination of base address and contract implemented by the service. For more information about default endpoints see Specifying an Endpoint Address. For more information about default endpoints, bindings, and behaviors, see Simplified Configuration and Simplified Configuration for WCF Services.

重点:在.net4.0以及更新的版本中,添加服务终结点是可选的。如果在代码或配置中没有添加终结点,那么wcf会为每一个基地址和服务实现的契约添加默认的终结点。

  • Step 4 – Enable metadata exchange. Clients will use metadata exchange to generate proxies that will be used to call the service operations. To enable metadata exchange create a ServiceMetadataBehaviorinstance, set it’s HttpGetEnabled property to true, and add the behavior to the Behaviors collection of the ServiceHost instance.

启用元数据交互。客户端使用元数据生成代理来调用服务操作。为了确保元数据交换,代码中需要创建一个ServiceMetadataBehavior对象,然后设置HttpGetEnabled属性为true。并且把这个行为添加到ServiceHost实例的Behaviors集合中。

  • Step 5 – Open the ServiceHost to listen for incoming messages. Notice the code waits for the user to hit enter. If you do not do this, the app will close immediately and the service will shut down.Also notice a try/catch block used. After the ServiceHost has been instantiated, all other code is placed in a try/catch block. For more information about safely catching exceptions thrown by ServiceHost, seeAvoiding Problems with the Using Statement

打开ServiceHost来监听进来的消息。注意代码在等待用户enter。如果你没有做这个的话,app会立即关闭并且服务也会被关闭。

还需要注意的是,使用了try catch进行异常的捕获。在ServiceHost实例化之后,所以的代码都放在了try catch块中。

To verify the service is working   确认托管服务已经在工作

  1. Run the GettingStartedHost console application from inside Visual Studio 2012. When running on Windows Vista and later operating systems, the service must be run with administrator privileges. Because Visual Studio was run with Administrator privileges, GettingStartedHost is also run with Administrator privileges. You can also start a new command prompt running it with Administrator privileges and run service.exe within it.

  2. Open Internet Explorer and browse to the service's debug page at http://localhost:8000/GettingStarted/CalculatorService.

1.在VS2012中运行GettingStartedHost控制台应用程序,vista之后的操作系统,必须以管理员权限来运行服务。因为VS2012是以管理员权限运行的,所以GettingStartedHost也是以管理员权限运行的。

你也可以启动cmd命令提示符,使用管理员权限运行。然后调用service.exe

2.打开浏览器,在http://localhost:8000/GettingStarted/CalculatorService浏览服务的调试页面

Notice:

Services such as this one require permission to register HTTP addresses on the machine for listening. Administrator accounts have this permission, but non-administrator accounts must be granted permission for HTTP namespaces. For more information about how to configure namespace reservations, see Configuring HTTP and HTTPS. When running under Visual Studio, the service.exe must be run with administrator privileges.

像这样的服务需要有权限在机器上注册Http地址来监听。管理员账号拥有这个权限,但是非管理员用户必须获得HTTP命名空间的授权。

上面的代码涉及到的类

System命名空间下的System.Uri

System.ServiceModel命名空间下的System.ServiceModel.ServiceHost

System.ServiceModel命名空间下的System.ServiceModel.WSHttpBinding

System.ServiceModel.Description命名空间下的System.ServiceModel.Description.ServiceMetadataBehavior

Step3 - How to: Host and Run a Basic Windows Communication Foundation Service的更多相关文章

  1. How to: Host and Run a Basic Windows Communication Foundation Service

    This is the third of six tasks required to create a Windows Communication Foundation (WCF) applicati ...

  2. A basic Windows service in C++ (CppWindowsService)

    A basic Windows service in C++ (CppWindowsService) This code sample demonstrates creating a basic Wi ...

  3. Cygwin Run in the Windows(Simulation of UNIX)

    Preface Environment Cygwin Run in the Windows(Simulation of UNIX) Resource Cygwin Install:http://cyg ...

  4. 修改host指定域名指向ip,Windows脚本与Linux脚本

    修改host指定域名指向ip,Windows脚本与Linux脚本 一,Windows系统修改hosts文件 Windows系统下hosts文件位置:C:\Windows\System32\driver ...

  5. .NET 5学习笔记(11)—— Host Blazor WebAssembly in a Windows Service

    实在是被某软忽悠瘸了,愤而写此一篇.希望能让同样需求的同学们少走弯路.某软在<在 Windows 服务中托管 ASP.NET Core>中,介绍了通过创建Worker Service工程, ...

  6. Run Redis On Windows

    If you go to the current version and open up the bin > release folder, you'll get a ZIP file cont ...

  7. How to: Define a Windows Communication Foundation Service Contract

    This is the first of six tasks required to create a basic Windows Communication Foundation (WCF) app ...

  8. Step1 - How to: Define a Windows Communication Foundation Service Contract

    https://msdn.microsoft.com/en-us/library/ms731835.aspx This is the first of six tasks required to cr ...

  9. 创建WCF的客户端

    How to: Create a Windows Communication Foundation Client To create a Windows Communication Foundatio ...

随机推荐

  1. 阅读笔记12-Java 面试题 —— 老田的蚂蚁金服面试经历

    电话一面 1.自我介绍.自己做的项目和技术领域 2.项目中的监控:那个监控指标常见的哪些? 3.微服务涉及到的技术以及需要注意的问题有哪些? 4.注册中心你了解了哪些? 5.consul 的可靠性你了 ...

  2. [12期]Mysql案例分析

    腾讯视频源:http://v.qq.com/vplus/0ef1d6371912bf6d083dce956f48556c 访问新闻版块,去掉?ID=X的参数以后报错 参数去掉,没有报错,显示正常,说明 ...

  3. python基础-3 集合 三元运算 深浅拷贝 函数 Python作用域

    上节课总结 1 运算符 in 字符串 判断  : “hello” in "asdasfhelloasdfsadf" 列表元素判断:"li" in ['li', ...

  4. The Log-Structured Merge-Tree(译)

    coming from http://duanple.blog.163.com/blog/static/7097176720120391321283/

  5. Java学习day11-类的成员之三:构造器(构造方法)

    一.构造器(构造方法) 语法格式: 修饰符 类名(参数列表){ 初始化语句: } 构造器的特征: 1.它具有与类相同的名称 2.它不声明返回值类型.(与声明为void不同) 3.不能被static.f ...

  6. 欧拉函数&欧拉定理&降幂 总结

    欧拉函数&欧拉定理&降幂 总结 标签:数学方法--数论 阅读体验:https://zybuluo.com/Junlier/note/1300214 这年头不总结一下是真的容易忘,老了老 ...

  7. SCUT - 131 - 小P玩游戏II - 贪心 - 平衡树

    https://scut.online/p/131 首先假如钦定了一群人去打怪兽,那么可以把主要的任务都丢给b最大的人去打,这样不会更差.然后考虑枚举这个b最大的人,其他人陪练.一开始就是ai+k*b ...

  8. 2019 Multi-University Training Contest 4 - 1010 - Minimal Power of Prime

    http://acm.hdu.edu.cn/showproblem.php?pid=6623 题意,给50000个1e18级别的数N,求它质因数分解里面的最小的指数(不算0) 比赛的时候给划了一个1e ...

  9. winform datagridview 绑定泛型集合变得不支持排序的解决方案

    原文:winform datagridview 绑定泛型集合变得不支持排序的解决方案 案例: 环境:Winform程序 控件:Datagridview 现象:Datagridview控件绑定到List ...

  10. 【推荐系统】知乎live入门2.细节补充

    参考链接 [推荐系统]知乎live入门 目录 1. 综述 2. 召回 3. 用户画像与标签 4. 特征工程 5. 点击率预估 6. 评估 7. 数据标注 8. 推荐 ================= ...