The WCF mechanism is really good. Although I don't know much about it, I only think from the perspective of the application, there are two notable ones: encapsulation communication and contract programming. The following is a demo to show how to deploy WCF in IIS. The demo server provides an operational service. The client calls the service according to the server contract to obtain the result.
1. Create a directory (IIS has access permissions, so do not create it in the system directory) iishostedcalcservice, and then create a file named service. SVC in the directory. The content is as follows:
<% @ Servicehost Language = C # DEBUG ="True"Service ="Microsoft. servicemodel. samples. calculatorservice"%>
This line declares the attributes of servicehost, such as the development language and service name.
2. Under the iishostedcalcservice directory, create the app_code directory and create a file named service. CS under app_code. The content of the file is as follows:
Using System; Using System. servicemodel; Namespace Microsoft. servicemodel. Samples {[servicecontract] Public Interface Icalculator {[operationcontract] Double Add ( Double N1, Double N2); [operationcontract] Double Subtract ( Double N1, Double N2); [operationcontract] Double Multiply ( Double N1, Double N2); [operationcontract] Double Divide ( Double N1, Double N2 );} Public Class Calculatorservice: icalculator { Public Double Add ( Double N1, Double N2 ){ Return N1 + N2 ;} Public Double Subtract ( Double N1, Double N2 ){ Return N1- N2 ;} Public Double Multiply ( Double N1, Double N2 ){ Return N1 * N2 ;} Public Double Divide ( Double N1, Double N2 ){ Return N1/ N2 ;}}}
This is one of the features mentioned above: Contract programming. Here, iclculater is the contract (do you see the servicecontract attribute modifier ?), The server publishes this contract to any clientCodeYou can use the contract-based code. (Isn't it an interface? Indeed ).
3. In the iishostedcalcservice directory, create a web. config file with the following content:
<? XML version = "1.0" encoding = "UTF-8" ?> < Configuration > < System. servicemodel > < Behaviors > < Servicebehaviors > < Behavior Name = "Calculatorservicebehavior" > < Servicemetadata Httpgetenabled = "True" /> </ Behavior > </ Servicebehaviors > </ Behaviors > < Services > <! -- This section is optional with the default configuration model introduced in. NET framework 4 --> < Service Name = "Microsoft. servicemodel. samples. calculatorservice" Behaviorconfiguration = "Calculatorservicebehavior" > <! -- This endpoint is exposed at the base address provided by host: http: // localhost/servicemodelsamples/service. SVC --> < Endpoint Address = "" Binding = "Wshttpbinding" Contract = "Microsoft. servicemodel. samples. icalculator" /> <! -- The Mex endpoint is exposed at http: // localhost/servicemodelsamples/service. svc/MEX --> < Endpoint Address = "Mex" Binding = "Mexhttpbinding" Contract = "Imetadataexchange" /> </ Service > </ Services > </ System. servicemodel > </ Configuration >
Because WCF requires the host to be on IIS, some configurations need to be made, which are put in Web. config. At runtime, WCF constructs an endpoint based on the information so that the client can communicate with it.
4. Now, the server code is written. Next let's take this WCFProgramDeploy it in IIS. First, confirm that you have installed. Net 4 and IIS 7. IIS 7 can be installed through the following installiis. BAT file (this bat needs to be run as an administrator). Its content is as follows:
Start/W ocsetup IIS-webserverrole; IIS-webserver; IIS-commonhttpfeatures; IIS-staticcontent; IIS-defaultdocument; IIS-directorybrowsing; IIS-httperrors; IIS-httpredirect; IIS-applicationdevelopment; IIS-ASPNET; IIS-netfxextensibility; IIS-ASP; IIS-CGI; IIS-isapiextensions; IIS-isapifilter; IIS-serversideincludes; IIS-healthanddiagnostics; IIS-httplogging; IIS-logginglibraries; IIS-requestmonitor; IIS-httptracing; IIS-customlogging; IIS-odbclogging; IIS-security; IIS-basicauthentication; IIS-windowsauthentication; IIS-digestauthentication; IIS-authentication; IIS-encryption; IIS-urlauthorization; IIS-requestfiltering; IIS-ipsecurity; IIS-performance; IIS-httpcompressionstatic; IIS-httpcompressiondynamic; IIS-webservermanagementtools; IIS-managementconsole; IIS-managementscriptingtools; IIS-managementservice; IIS-IIS6ManagementCompatibility; IIS-metabase; IIS-wmicompatibility; IIS-legacyscripts; IIS-legacysnapin; IIS-ftpserver; was-windowsactivationservice; was-processmodel; was-activationapi; IIS-WebDAV; IIS-ftpsvc; IIS-ftpextensibilityc: CD c: \ windows \ system32 \ character set config/section: defaultdocumentappcmd add apppool/name: "myapppool"/managedpipelinemode: integrated/managedruntimeversion: v4.0 % WinDir % \ Microsoft. net \ framework64 \ v4.0.30319 \ aspnet_regiis.exe-IR
5. Choose Control Panel> Administrative Tools> Internet Information Service Manager, right-click the default web site, and select Add application from the pop-up menu. (myapppool is.. Net 4 Application pool. If not, create one first)
6. Test it. Enter http: // localhost/iishostedcalc/service. SVC in the browser and you will see the following prompt (note that yourhost is your host's hostname ):
The calculatorservice service has been created. To test the service, you need to create a client and use it to call the service. You can use the following syntax to perform this operation from the command line: svcutil.exe http ://Yourhost/Iishostedcalc/service. SVC? WSDL generates a configuration file and a code file containing the client class. Add these two files to the client application and use the generated client class to call the service. For example, C # class test {static void main () {calculatorclient Client client = new calculatorclient (); // use the "client" variable to call the operation on the service. // Always close the client. Client. Close () ;}} visual basicclass test shared sub main () dim client as calculatorclient = new calculatorclient () 'use the "client" variable to call the operation on the service. 'Always close the client. Client. Close () end subend class
7. After the server is deployed, the client code is compiled as prompted. First, add c: \ Program Files (x86) \ microsoft sdks \ windows \ v7.0a \ bin to the system variable path (to facilitate the use of the svcutil command on the command line ). Create a client directory under the iishostedcalcservice directory, enter the client directory from the command line, and enter the command:
Svcutil http: // yourhost/iishostedcalc/service. SVC? WSDL
You can generate the contract (calculatorservice. CS) required by the client and the configuration file (Out. config) required to communicate with the server ):
8. Compile the console client test program. Create a C # console program and change main ():
VaR client = new calculatorclient (); // use the "client" variable to call the operation on the service. Double I = client. Add (100, 23); console. writeline ("> Add result {0}", I); // always close the client. Client. Close (); console. readkey ();
Add calculatorservice. CS to the project, change out. config to app. config, and set copy If newer as the copy policy of APP. config. Modify app. config to (note that yourhost is your host name, which is consistent with the one displayed on the prompt page ):
<? XML version = "1.0" encoding = "UTF-8" ?> < Configuration > < System. servicemodel > < Bindings > < Wshttpbinding > < Binding Name = "Wshttpbinding_icalculator" Closetimeout = "00:01:00" Opentimeout = "00:01:00" Receivetimeout = "00:10:00" Sendtimeout = "00:01:00" Bypassproxyonlocal = "False" Transactionflow = "False" Hostnamecomparisonmode = "Strongwildcard" Maxbufferpoolsize = "524288" Maxcompute edmessagesize = "65536" Messageencoding = "Text" Textencoding = "UTF-8" Usedefawebwebproxy = "True" Allowcookies = "False" > < Readerquotas Maxdepth = "32" Maxstringcontentlength = "8192" Maxarraylength = "16384" Maxbytesperread = "4096" Maxnametablecharcount = "16384" /> < Reliablesession Ordered = "True" Inactivitytimeout = "00:10:00" Enabled = "False" /> < Security Mode = "Message" > < Transport Clientcredentialtype = "Windows" Proxycredentialtype = "NONE" Realm = "" /> < Message Clientcredentialtype = "Windows" Negotiateservicecredential = "True" Algorithmsuite = "Default" Establishsecuritycontext = "True" /> </ Security > </ Binding > </ Wshttpbinding > </ Bindings > < Client > < Endpoint Address = "Http ://Yourhost/Iishostedcalc/service. SVC" Binding = "Wshttpbinding" Bindingconfiguration = "Wshttpbinding_icalculator" Contract = "Icalculator" Name = "Wshttpbinding_icalculator" > < Identity > < Serviceprincipalname Value = "Host/Yourhost" /> </ Identity > </ Endpoint > </ Client > </ System. servicemodel > </ Configuration >
9. Add the system. servicemodel and system. serviceprocess references to the project, and compile and run them. In conclusion, the client calls the server code and returns the result:
10. Note that it is very convenient to deploy WCF to IIS. However, due to the low permission of IIS, it is usually not feasible. To perform operations with higher permissions (such as writing disk files to any disk), you can deploy WCF to window service.
Reference link:
How to: host a WCF Service in IIS