WCF Web HTTP 编程模型概述WCF Web HTTP Programming Model Overview

Windows Communication Foundation (WCF) WEB HTTP 编程模型提供了用 WCF 生成 WEB HTTP 服务所需的基本元素。The Windows Communication Foundation (WCF) WEB HTTP programming model provides the basic elements required to build WEB HTTP services with WCF. WCF WEB HTTP 服务旨在由最大范围的可能客户端(包括 Web 浏览器)访问,并且具有以下独特要求:WCF WEB HTTP services are designed to be accessed by the widest range of possible clients, including Web browsers and have the following unique requirements:

  • Uri 和 Uri 处理Uri 在 WEB HTTP 服务的设计中扮演着一个中心角色。URIs and URI Processing URIs play a central role in the design of WEB HTTP services. WCF WEB HTTP 编程模型使用 UriTemplateUriTemplateTable 类来提供 URI 处理功能。The WCF WEB HTTP programming model uses the UriTemplate and UriTemplateTable classes to provide URI processing capabilities.

  • 支持 GET 和 POST 操作WEB HTTP 服务除了使用各种调用谓词来进行数据修改和远程调用以外,还使用 GET 谓词进行数据检索。Support for GET and POST operations WEB HTTP services make use of the GET verb for data retrieval, in addition to various invoke verbs for data modification and remote invocation. WCF WEB HTTP 编程模型使用 WebGetAttributeWebInvokeAttribute 将服务操作与 GET 和其他 HTTP 谓词(如 PUT、POST 和 DELETE)相关联。The WCF WEB HTTP programming model uses the WebGetAttribute and WebInvokeAttribute to associate service operations with both GET and other HTTP verbs like PUT, POST, and DELETE.

  • 多种数据格式除了 SOAP 消息以外,Web 样式服务还处理多种类型的数据。Multiple data formats Web-style services process many kinds of data in addition to SOAP messages. WCF WEB HTTP 编程模型使用 WebHttpBindingWebHttpBehavior 来支持多种不同的数据格式,包括 XML 文档、JSON 数据对象和二进制内容(如图像、视频文件或纯文本)的流。The WCF WEB HTTP programming model uses the WebHttpBinding and WebHttpBehavior to support many different data formats including XML documents, JSON data object, and streams of binary content such as images, video files, or plain text.

WCF WEB HTTP 编程模型扩展了 WCF 的覆盖范围,以涵盖包括 WEB HTTP 服务、AJAX 和 JSON 服务以及联合(ATOM/RSS)源的 Web 样式方案。The WCF WEB HTTP programming model extends the reach of WCF to cover Web-style scenarios that include WEB HTTP services, AJAX and JSON services, and Syndication (ATOM/RSS) feeds. 有关 AJAX 和 JSON 服务的详细信息,请参阅Ajax 集成和 Json 支持For more information about AJAX and JSON services, see AJAX Integration and JSON Support. 有关联合的详细信息,请参阅WCF 联合概述For more information about Syndication, see WCF Syndication Overview.

对于可从 WEB HTTP 服务返回的数据的类型没有额外的限制。There are no extra restrictions on the types of data that can be returned from a WEB HTTP service. 任何可序列化类型都可以从 WEB HTTP 服务操作返回。Any serializable type can be returned from an WEB HTTP service operation. 因为 WEB HTTP 服务操作可以通过 Web 浏览器调用,所以对可在 URL 中指定的数据类型有一个限制。Because WEB HTTP service operations can be invoke by a web browser there is a limitation on what data types can be specified in a URL. 有关默认情况下支持的类型的详细信息,请参阅下面的UriTemplate 查询字符串参数和 url部分。For more information on what types are supported by default see the UriTemplate Query String Parameters and URLs section below. 通过提供您自己的 T:System.ServiceModel.Dispatcher.QueryStringConverter 实现来指定如何将 URL 中指定的参数转换为实际参数类型,可以更改默认行为。The default behavior can be changed by providing your own T:System.ServiceModel.Dispatcher.QueryStringConverter implementation which specifies how to convert the parameters specified in a URL to the actual parameter type. 有关详细信息,请参阅QueryStringConverterFor more information, see QueryStringConverter


使用 WCF WEB HTTP 编程模型编写的服务不使用 SOAP 消息。Services written with the WCF WEB HTTP programming model do not use SOAP messages. 由于不使用 SOAP,因此不能使用 WCF 提供的安全功能。Because SOAP is not used, the security features provided by WCF cannot be used. 然而,您可以通过使用 HTTPS 承载服务来使用基于传输的安全性。You can, however use transport-based security by hosting your service with HTTPS. 有关 WCF 安全的详细信息,请参阅安全性概述For more information about WCF security, see Security Overview


为 IIS 安装 WebDAV 扩展会导致 Web HTTP 服务返回 HTTP 405 错误,因为 WebDAV 扩展试图处理所有 PUT 请求。Installing the WebDAV extension for IIS can cause Web HTTP services to return an HTTP 405 error as the WebDAV extension attempts to handle all PUT requests. 若要解决此问题,你可卸载 WebDAV 扩展或为网站禁用 WebDAV 扩展。To work around this issue you can uninstall the WebDAV extension or disable the WebDAV extension for your web site. 有关详细信息,请参阅IIS 和 WebDavFor more information, see IIS and WebDav

使用 UriTemplate 和 UriTemplateTable 进行 URI 处理URI Processing with UriTemplate and UriTemplateTable

URI 模板提供了一种可以高效地表示很大的结构相似的 URI 集的语法。URI templates provide an efficient syntax for expressing large sets of structurally similar URIs. 例如,下面的模板表示所有以“a”开始并以“c”结束而中间段的值不限的、由三个段组成的 URI:a/{segment}/cFor example, the following template expresses the set of all three-segment URIs that begin with "a" and end with "c" without regard to the value of the intermediate segment: a/{segment}/c

此模板描述如下所示的 URI:This template describes URIs like the following:

  • a/x/ca/x/c

  • a/y/ca/y/c

  • a/z/ca/z/c

  • 等等。and so on.

在此模板中,大括号表示法 ("{segment}") 指示变量段而不是文本值。In this template, the curly brace notation ("{segment}") indicates a variable segment instead of a literal value.

.NET Framework 提供了一个 API 来处理名为 UriTemplate 的 URI 模板。.NET Framework provides an API for working with URI templates called UriTemplate. UriTemplates 允许执行下列操作:UriTemplates allow you to do the following:

  • 您可以 Bind 使用一组参数调用其中一个方法来生成与模板匹配的完全关闭的 URIYou can call one of the Bind methods with a set of parameters to produce a fully-closed URI that matches the template. 这意味着,URI 模板中的所有变量均由实际值替换。This means all variables within the URI template are replaced with actual values.

  • 可以使用候选 URI 调用 Match(),此时会使用模板将候选 URI 的各个组成部分分解开来,并会返回一个字典,其中包含根据模板中的变量标记的 URI 的不同部分。You can call Match() with a candidate URI, which uses a template to break up a candidate URI into its constituent parts and returns a dictionary that contains the different parts of the URI labeled according to the variables in the template.

  • Bind() 和 Match() 互为逆方法,因此可以调用 Match( Bind( x ) ) 并返回到开始时的相同环境。Bind() and Match() are inverses so that you can call Match( Bind( x ) ) and come back with the same environment you started with.

在很多时候(尤其是在服务器需要基于 URI 将请求调度到某个服务操作时),对于那些可以单独对包含的每个模板进行寻址的数据结构,您需要一直跟踪其中的一组 UriTemplate 对象。There are many times (especially on the server, where dispatching a request to a service operation based on the URI is necessary) that you want to keep track of a set of UriTemplate objects in a data structure that can independently address each of the contained templates. UriTemplateTable 表示一组 URI 模板,并在给定的一组模板和候选 URI 中选择最匹配的项。UriTemplateTable represents a set of URI templates and selects the best match given a set of templates and a candidate URI. 这并不隶属于任何特定的网络堆栈(包括 WCF),因此可以在必要时使用。This is not affiliated with any particular networking stack (WCF included) so you can use it wherever necessary.

WCF 服务模型使用 UriTemplateUriTemplateTable 将服务操作与由 UriTemplate 描述的一组 URI 相关联。The WCF Service Model makes use of UriTemplate and UriTemplateTable to associate service operations with a set of URIs described by a UriTemplate. 通过使用 UriTemplateWebGetAttribute,将服务操作与 WebInvokeAttribute 相关联。A service operation is associated with a UriTemplate, using either the WebGetAttribute or the WebInvokeAttribute. 有关和的详细 UriTemplate 信息 UriTemplateTable ,请参阅UriTemplate 和 UriTemplateTableFor more information about UriTemplate and UriTemplateTable, see UriTemplate and UriTemplateTable

WebGet 和 WebInvoke 特性WebGet and WebInvoke Attributes

WCF WEB HTTP 服务除了使用各种调用谓词(例如 HTTP POST、PUT 和 DELETE)之外,还使用检索谓词(例如 HTTP GET)。WCF WEB HTTP services make use of retrieval verbs (for example HTTP GET) in addition to various invoke verbs (for example HTTP POST, PUT, and DELETE). WCF WEB HTTP 编程模型允许服务开发人员通过和控制与其服务操作相关联的 URI 模板和谓词 WebGetAttribute WebInvokeAttributeThe WCF WEB HTTP programming model allows service developers to control the both the URI template and verb associated with their service operations with the WebGetAttribute and WebInvokeAttribute. 可以使用 WebGetAttributeWebInvokeAttribute 来控制各个操作如何绑定到 URI 以及与这些 URI 相关联的 HTTP 方法。The WebGetAttribute and the WebInvokeAttribute allow you to control how individual operations get bound to URIs and the HTTP methods associated with those URIs. 例如,在下面的代码中添加 WebGetAttributeWebInvokeAttributeFor example, adding WebGetAttribute and WebInvokeAttribute in the following code.

interface ICustomer  
  //"View It"  
  Customer GetCustomer():  
  //"Do It"  
  Customer UpdateCustomerName( string id,
                               string newName );  

可以使用上面的代码生成下面的 HTTP 请求。The preceding code allows you to make the following HTTP requests.

GET /GetCustomer

POST /UpdateCustomerName

WebInvokeAttribute 的默认值为 POST,但也可以将其用于其他谓词。WebInvokeAttribute defaults to POST but you can use it for other verbs too.

interface ICustomer  
  //"View It" -> HTTP GET  
    [WebGet( UriTemplate="customers/{id}" )]  
  Customer GetCustomer( string id ):  
  //"Do It" -> HTTP PUT  
  [WebInvoke( UriTemplate="customers/{id}", Method="PUT" )]  
  Customer UpdateCustomer( string id, Customer newCustomer );  

若要查看使用 WCF WEB HTTP 编程模型的 WCF 服务的完整示例,请参阅如何:创建基本 WCF WEB Http 服务To see a complete sample of a WCF service that uses the WCF WEB HTTP programming model, see How to: Create a Basic WCF Web HTTP Service

UriTemplate 查询字符串参数和 URLUriTemplate Query String Parameters and URLs

可以通过键入与服务操作相关联的 URL 来从 Web 浏览器调用 Web 样式服务。Web-style services can be called from a Web browser by typing a URL that is associated with a service operation. 这些服务操作可以采用查询字符串参数,必须在 URL 内使用字符串格式指定这些参数。These service operations may take query string parameters that must be specified in a string form within the URL. 下表演示可以在 URL 内传递的类型和使用的格式。The following table shows the types that can be passed within a URL and the format used.

类型Type 格式Format
Byte 0 - 2550 - 255
SByte -128 - 127-128 - 127
Int16 -32768 - 32767-32768 - 32767
Int32 -2,147,483,648 - 2,147,483,647-2,147,483,648 - 2,147,483,647
Int64 -9,223,372,036,854,775,808 - 9,223,372,036,854,775,807-9,223,372,036,854,775,808 - 9,223,372,036,854,775,807
UInt16 0 - 655350 - 65535
UInt32 0 - 4,294,967,2950 - 4,294,967,295
UInt64 0 - 18,446,744,073,709,551,6150 - 18,446,744,073,709,551,615
Single -3.402823e38 - 3.402823e38(不需要指数表示法)-3.402823e38 - 3.402823e38 (exponent notation is not required)
Double -1.79769313486232e308 - 1.79769313486232e308(不需要指数表示法)-1.79769313486232e308 - 1.79769313486232e308 (exponent notation is not required)
Char 任何单个字符Any single character
Decimal 使用标准表示法的任何小数(无指数)Any decimal in standard notation (no exponent)
Boolean True 或 False(不区分大小写)True or False (case insensitive)
String 任何字符串(不支持空字符串,且不进行转义)Any string (null string is not supported and no escaping is done)


月、日、年Month Day Year

月份日期年 HH: MM: SS [AM|PM]Month Day Year HH:MM:SS [AM|PM]

此处,DD = 天、HH = 小时、MM = 分钟、SS = 秒钟Where DD = Days, HH = Hours, MM = minutes, SS = Seconds
Guid 一个 GUID,例如:A GUID, for example:


此处,DD = 天、HH = 小时、MM = 分钟、SS = 秒钟Where DD = Days, HH = Hours, MM = minutes, SS = Seconds
枚举Enumerations 例如,定义枚举的枚举值,如以下代码中所示。The enumeration value for example, which defines the enumeration as shown in the following code.

public enum Days{ Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

可以在查询字符串中指定任何单独的枚举值(或其对应的整数值)。Any of the individual enumeration values (or their corresponding integer values) may be specified in the query string.
具有可在类型和字符串表示形式之间来回进行转换的 TypeConverterAttribute 的类型。Types that have a TypeConverterAttribute that can convert the type to and from a string representation. 取决于类型转换器。Depends on the Type Converter.

格式和 WCF WEB HTTP 编程模型Formats and the WCF WEB HTTP Programming Model

WCF WEB HTTP 编程模型具有用于处理多种不同数据格式的新功能。The WCF WEB HTTP programming model has new features to work with many different data formats. 在绑定层上,WebHttpBinding 可以读取和写入下列不同种类的数据:At the binding layer, the WebHttpBinding can read and write the following different kinds of data:



  • 不透明二进制流Opaque binary streams

这意味着 WCF WEB HTTP 编程模型可以处理任何类型的数据,但您可能会对进行编程 StreamThis means the WCF WEB HTTP programming model can handle any type of data but, you may be programming against Stream.

.NET Framework 3.5 支持 JSON 数据(AJAX)和联合源(包括 ATOM 和 RSS)。.NET Framework 3.5 provides support for JSON data (AJAX) as well as Syndication feeds (including ATOM and RSS). 有关这些功能的详细信息,请参阅Wcf WEB HTTP 格式设置wcf 联合概述以及AJAX 集成和 JSON 支持For more information about these features, see WCF Web HTTP Formatting, WCF Syndication Overview, and AJAX Integration and JSON Support.

WCF WEB HTTP 编程模型和安全WCF WEB HTTP Programming Model and Security

由于 WCF WEB HTTP 编程模型不支持 WS-* 协议,因此保证 WCF WEB HTTP 服务安全的唯一方式是使用 SSL 通过 HTTPS 公开服务。Because the WCF WEB HTTP programming model does not support the WS-* protocols, the only way to secure a WCF WEB HTTP service is to expose the service over HTTPS using SSL. 有关设置 SSL 和 IIS 7.0 的详细信息,请参阅如何在 iis 中实现 sslFor more information about setting up SSL with IIS 7.0, see How to implement SSL in IIS.

WCF WEB HTTP 编程模型疑难解答Troubleshooting the WCF WEB HTTP Programming Model

当使用 ChannelFactoryBase<TChannel> 调用 WCF WEB HTTP 服务以创建通道时,即使将其他 WebHttpBehavior 传递给 EndpointAddressEndpointAddress 也会使用配置文件中设置的 ChannelFactoryBase<TChannel>When calling WCF WEB HTTP services using a ChannelFactoryBase<TChannel> to create a channel, the WebHttpBehavior uses the EndpointAddress set in the configuration file even if a different EndpointAddress is passed to the ChannelFactoryBase<TChannel>.

另请参阅See also