Introduction to WCF features in the REST Architecture

Source: Internet
Author: User
Tags representational state transfer

As an outstanding architectural style, restful (Representational State Transfer) has been favored by developers since its birth. For developers who have never been familiar with REST, refer to my previous blog: understanding of REST architecture and Jquery + JSON + RESTful WCF.

 

What features does REST have due to its simplicity and HTTP-based features .? This topic is divided into two parts and introduced in conjunction with the Demo program. The first part introduces the knowledge points involved, and the second part introduces the Demo.


 The main knowledge points involved are as follows:
1. binding protocols and behaviors (webHttpBinding and webHttpBehavior)
2. Define actions (POST, GET, DELETE, and PUT)
3. URI (Uniform Resource Identifier)
4. webServiceHost and webServiceHostFactory

* 1. binding protocols and behaviors (webHttpBinding and webHttpBehavior)
As we all know, there are many protocols supported in WCF, such as wsHttpBinding and other ws-* series, netTcpBinding, and MSMQ series protocols. In building a REST architecture-style WCF
The protocol we use is webHttpBinding. The corresponding behavior is webHttpBehavior.

MSDN describes them as follows:
WebHttpBinding: a binding that can be used to configure endpoints for Windows Communication Foundation (WCF) Web Services exposed through HTTP requests (instead of SOAP messages.
WebHttpBehavior: enables the Web programming model of the Windows Communication Foundation (WCF) service.
When WebHttpBehavior behavior is bound with WebHttpBinding, it supports open and access to the Web style service by WCF.WebServiceHost automatically adds this behavior to the endpoint using WebHttpBinding.
WebHttpBinding is the protocol used by WCF in the REST architecture. Like other protocols, webHttpBinding notifies WCF of how to create a Channel stack for communication, that is, to create a Channel
Communication. WebHttpBehavior is used to configure the behavior of rest wcf endpoints. It determines how WebHttpDispatchOperationSelector decides the routing method to choose.
To access resources.
* 2. Each verb in the Action determines the operation on the resource.
POST: Add resources known to the client. It is the default action of WebInvokeAttribute.
Get: gets the resource. It is the default action of WebGetAttribute.
DELETE: DELETE a resource. Generally, this parameter is specified by WebInvokeAttribute.
PUT: Add or modify resources. Generally, this parameter is specified by WebInvokeAttribute.

* 3. URI
The URI (Uniform Resource Identifier) is identified by the WebGetAttribute and WebInvokeAttribute features in the rest wcf programming model. It passes
The UriTemplate attribute of the WebGetAttribute and WebInvokeAttribute attributes is specified. It is usually specified on the Interface corresponding to the service contract. WebHttpDispathOperationSelector is determined by URI.
Perform operations on resources. The example is defined as follows:
[OperationContract]
[WebGet (UriTemplate = "/")]
List <LogEntity> GetAll ();

* 4. webServiceHost and webServiceHostFactory
Some people who know about WCF know that its configuration is complicated. REST emphasizes simplicity. Therefore, in the rest wcf programming model, MS introduces webServiceHost
And webServiceHostFactory to simplify our configuration. WebServiceHost is inherited from ServiceHost. using it, we no longer need
WebHttpBehavior is configured. webServiceHost automatically creates an endpoint and configures it using webHttpBinding and webHttpBehavior.
Descriptions of webServiceHost in MSDN are as follows:
If the endpoint cannot be found in the service description, WebServiceHost automatically creates a default endpoint for the HTTP and HTTPS base addresses in the base address of the service. If you have explicitly configured the base address
It does not automatically create an endpoint. WebServiceHost automatically configures the end point binding for use in the security virtual directory with the associated Internet Information Service (IIS) security settings.
When the default HTTP endpoint is created, WebServiceHost disables both the HTTP help page and the Web Service Description Language (WSDL) GET function, so that the metadata endpoint does not interfere with the default HTTP endpoint.
In addition, the WebServiceHost class adds WebHttpBehavior to all endpoints that do not have this behavior but have WebMessageEncodingElement. If all operations on the service have
If an empty HTTP Request body or both of the HTTP request bodies are processed as streams, the WebServiceHost automatically configures an appropriate content type ER for the binding.
Note: It disables the help page in rest wcf.
WebServiceHostFactory, inherited from ServiceHostFactory, uses it, we do not need to configure rest wcf, just need to specify it in the svc FILE command. Example:
<% @ ServiceHost Service = "LogServices. LogServices" Factory = "System. ServiceModel. Activation. WebServiceHostFactory" %>
It must be noted that the Service attribute must be specified as a class for implementing the Service contract.
Part 2: Demo sample program.
Development Environment: VS2008 SP1
The program structure is as follows:


Contracts: defines a service contract.
The Code is as follows:

 

 

 

01 [ServiceContract]

02 public interface Ilog

03 {

04 [OperationContract]

05 [WebGet (UriTemplate = "/")]

06 List <LogEntity> GetAll ();

07

08 [OperationContract]

09 [WebGet (UriTemplate = "Get/{year}/{month}")]

10 List <LogEntity> GetMonthLog (string year, stringmonth );

11}

12 [DataContract]

13. public class LogEntity

14 {

15 [DataMember]

16 public int ID {get; set ;}

17

18 [DataMember]

19 public string EventName {get; set ;}

20

21 [DataMember]

22 public string Level {get; set ;}

23

24 [DataMember]

25 public DateTime Time {get; set ;}

26

27}

  

 

LogServices: Implements service contracts and provides services.

The Code is as follows:

 

View sourceprint?

01 public List <LogEntity> GetAll ()

02 {

03 return GetLogEntityList ();

04}

05

06 public List <LogEntity> GetMonthLog (string year, string month)

07 {

08 List <LogEntity> logEntities = GetLogEntityList ();

09 List <LogEntity> logList = new List <LogEntity> ();

10 logEntities. ForEach (log =>

11 {

12 if (log. Time. Year. ToString () = year & log. Time. Month. ToString () = month)

13 {

14 logList. Add (log );

15}

16 });

17 return logList;

18

19}

 

 

By the way, you can check the configuration file. You do not need to configure WCF when using WebServiceHostFactory. The configuration file is as follows:

 

 

Show sourceview sourceprint?

001 <? Xml version = "1.0"?>

002 <configuration>

003 <configSections>

004 <sectionGroup name = "system. web. extensions "type =" System. web. configuration. systemWebExtensionsSectionGroup, System. web. extensions, Version = 3.5.0.0, Culture = neutral, PublicKeyToken = 31BF3856AD364E35 ">

005 <sectionGroup name = "scripting" type = "System. Web. Configuration. ScriptingSectionGroup, System. Web. Extensions, Version = 3.5.0.0, Culture = neutral, PublicKeyToken = 31BF3856AD364E35">

006 <section name = "scriptResourceHandler" type = "System. web. configuration. scriptingScriptResourceHandlerSection, System. web. extensions, Version = 3.5.0.0, Culture = neutral, PublicKeyToken = 31BF3856AD364E35 "requirePermission =" false "allowDefinition =" MachineToApplication "/>

007 <sectionGroup name = "webServices" type = "System. Web. Configuration. ScriptingWebServicesSectionGroup, System. Web. Extensions, Version = 3.5.0.0, Culture = neutral, PublicKeyToken = 31BF3856AD364E35">

008 <section name = "jsonSerialization" type = "System. web. configuration. scriptingJsonSerializationSection, System. web. extensions, Version = 3.5.0.0, Culture = neutral, PublicKeyToken = 31BF3856AD364E35 "requirePermission =" false "allowDefinition =" Everywhere "/>

009 <section name = "profileService" type = "System. web. configuration. scriptingProfileServiceSection, System. web. extensions, Version = 3.5.0.0, Culture = neutral, PublicKeyToken = 31BF3856AD364E35 "requirePermission =" false "allowDefinition =" MachineToApplication "/>

 

010 <section name = "authenticationService" type = "System. web. configuration. scriptingAuthenticationServiceSection, System. web. extensions, Version = 3.5.0.0, Culture = neutral, PublicKeyToken = 31BF3856AD364E35 "requirePermission =" false "allowDefinition =" MachineToApplication "/>

011 <section name = "roleService" type = "System. web. configuration. scriptingRoleServiceSection, System. web. extensions, Version = 3.5.0.0, Culture = neutral, PublicKeyToken = 31BF3856AD364E35 "requirePermission =" false "allowDefinition =" MachineToApplication "/>

012 </sectionGroup>

013 </sectionGroup>

014 </sectionGroup>

015 </configSections>

016 <appSettings/>

017 <connectionStrings/>

018 <system. web>

019 <! --

020 set compilation debug = "true" to insert debugging symbols

021 compiled pages. However, this

022 affects performance, so this value is only available during development

Set 023 to true.

024 -->

025 <compilation debug = "true">

026 <assemblies>

027 <add assembly = "System. Core, Version = 3.5.0.0, Culture = neutral, PublicKeyToken = B77A5C561934E089"/>

028 <add assembly = "System. Data. DataSetExtensions, Version = 3.5.0.0, Culture = neutral, PublicKeyToken = B77A5C561934E089"/>

029 <add assembly = "System. Web. Extensions, Version = 3.5.0.0, Culture = neutral, PublicKeyToken = 31BF3856AD364E35"/>

030 <add assembly = "System. Xml. Linq, Version = 3.5.0.0, Culture = neutral, PublicKeyToken = B77A5C561934E089"/>

031 </assemblies>

032 </compilation>

033 <! --

034 use the <authentication> section to configure ASP. NET

035 identifies

036 Security Authentication mode.

037 -->

038 <authentication mode = "Windows"/>

039 <! --

040 if an unprocessed error occurs during request execution,

041, you can configure the corresponding processing steps in the <mermerrors> section. Specifically,

042 developers can configure through this section

043 html error page to be displayed

044 to replace the error stack trace.

045

046 <customErrors mode = "RemoteOnly" defaultRedirect = "GenericErrorPage.htm">

047 <error statusCode = "403" redirect = "NoAccess.htm"/>

048 <error statusCode = "404" redirect = "FileNotFound.htm"/>

049 </customErrors>

050 -->

051 <pages>

052 <controls>

053 <add tagPrefix = "asp" namespace = "System. Web. UI" assembly = "System. Web. Extensions, Version = 3.5.0.0, Culture = neutral, PublicKeyToken = 31BF3856AD364E35"/>

054 <add tagPrefix = "asp" namespace = "System. web. UI. webControls "assembly =" System. web. extensions, Version = 3.5.0.0, Culture = neutral, PublicKeyToken = 31BF3856AD364E35 "/>

055 </controls>

056 </pages>

057

058 <remove verb = "*" path = "*. asmx"/>

059 <add verb = "*" path = "*. asmx "validate =" false "type =" System. web. script. services. scriptHandlerFactory, System. web. extensions, Version = 3.5.0.0, Culture = neutral, PublicKeyToken = 31BF3856AD364E35 "/>

060 <add verb = "*" path = "* _ AppService. axd "validate =" false "type =" System. web. script. services. scriptHandlerFactory, System. web. extensions, Version = 3.5.0.0, Culture = neutral, PublicKeyToken = 31BF3856AD364E35 "/>

061 <add verb = "GET, HEAD" path = "ScriptResource. axd "type =" System. web. handlers. scriptResourceHandler, System. web. extensions, Version = 3.5.0.0, Culture = neutral, PublicKeyToken = 31BF3856AD364E35 "validate =" false "/>

062

063

064 <add name = "ScriptModule" type = "System. Web. Handlers. ScriptModule, System. Web. Extensions, Version = 3.5.0.0, Culture = neutral, PublicKeyToken = 31BF3856AD364E35"/>

065

066 </system. web>

067 <system. codedom>

068 <compilers>

069 <compiler language = "c #; cs; csharp" extension = ". cs "warningLevel =" 4 "type =" Microsoft. CSharp. CSharpCodeProvider, System, Version = 2.0.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089 ">

070 <providerOption name = "CompilerVersion" value = "v3.5"/>

071 <providerOption name = "WarnAsError" value = "false"/>

072 </compiler>

073 </compilers>

074 </system. codedom>

075 <! --

076 running ASP. net ajax in Internet Information Service 7.0 requires system. webServer

Section 077. This section is not required for earlier versions of IIS.

078 -->

079 <system. webServer>

080 <validation validateIntegratedModeConfiguration = "false"/>

081 <modules>

082 <remove name = "ScriptModule"/>

083 <add name = "ScriptModule" preCondition = "managedHandler" type = "System. web. handlers. scriptModule, System. web. extensions, Version = 3.5.0.0, Culture = neutral, PublicKeyToken = 31BF3856AD364E35 "/>

084 </modules>

085

086 <remove name = "WebServiceHandlerFactory-Integrated"/>

087 <remove name = "ScriptHandlerFactory"/>

088 <remove name = "ScriptHandlerFactoryAppServices"/>

089 <remove name = "ScriptResource"/>

090 <add name = "ScriptHandlerFactory" verb = "*" path = "*. asmx "preCondition =" integratedMode "type =" System. web. script. services. scriptHandlerFactory, System. web. extensions, Version = 3.5.0.0, Culture = neutral, PublicKeyToken = 31BF3856AD364E35 "/>

091 <add name = "ScriptHandlerFactoryAppServices" verb = "*" path = "* _ AppService. axd "preCondition =" integratedMode "type =" System. web. script. services. scriptHandlerFactory, System. web. extensions, Version = 3.5.0.0, Culture = neutral, PublicKeyToken = 31BF3856AD364E35 "/>

092 <add name = "ScriptResource" preCondition = "integratedMode" verb = "GET, HEAD" path = "ScriptResource. axd "type =" System. web. handlers. scriptResourceHandler, System. web. extensions, Version = 3.5.0.0, Culture = neutral, PublicKeyToken = 31BF3856AD364E35 "/>

093

094 </system. webServer>

095 <runtime>

096 <assemblyBinding xmlns = "urn: schemas-microsoft-com: asm. v1">

097 <dependentAssembly>

098 <assemblyIdentity name = "System. Web. Extensions" publicKeyToken = "31bf3856ad364e35"/>

099 <bindingRedirect oldVersion = "1.0.0.0-1.1.0.0" newVersion = "3.5.0.0"/>

100 </dependentAssembly>

101 <dependentAssembly>

102 <assemblyIdentity name = "System. Web. Extensions. Design" publicKeyToken = "31bf3856ad364e35"/>

103 <bindingRedirect oldVersion = "1.0.0.0-1.1.0.0" newVersion = "3.5.0.0"/>

104 </dependentAssembly>

105 </assemblyBinding>

106 </runtime>

107 <! -- <System. serviceModel>

108

109 </system. serviceModel> -->

110 </configuration>

  

 

 

RESTWCFDemo: Host service, and call the service. Because the host of the rest wcf Service requires IIS, the client and server of the program are directly placed under a Web project.
Call the service in IE to view the running effect.
1. Call List <LogEntity> GetAll (). The result is as follows:

2. Call GetMonthLog. The result is as follows:

 

Author: tyb1222

<Script> </script>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.