WCF Getting Started Tutorial (ii) starting from scratch-creating a WCF Service

Source: Internet
Author: User

See how the simplest WCF is implemented with the most basic operations. This is the default sample created by the SDK for VS

1. Create a WCF service library

2, look at its generation structure

1) IService1.cs (protocol)

Defines the protocol, what the operation, the parameters of the operation, and the return value of the information

By ServiceContract, OperationContract, DataContract, DataMember and other attribute parameters, the service, operation and data structure are defined clearly.

Here we also see clearly that the WCF Service transport data types are not only common data types, but also can transfer custom complex types. Which fields are to be transferred can be specified by the DataMember tag.

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Runtime.Serialization;usingSystem.ServiceModel;usingSystem.Text;namespacesecondwcfsample{//Note: Using the rename command on the Refactor menu, you can change the interface name "IService1" in code and configuration files at the same time. [ServiceContract] Public InterfaceIService1 {[OperationContract]stringGetData (intvalue);        [OperationContract]        Compositetype getdatausingdatacontract (Compositetype composite); //TODO: Add your service actions here    }    //use the data contract described in the following example to add a composite type to a service operation[DataContract] Public classCompositetype {BOOLBoolvalue =true; stringStringValue ="Hello"; [DataMember] Public BOOLBoolvalue {Get{returnBoolvalue;} Set{Boolvalue =value;} } [DataMember] Public stringStringValue {Get{returnStringValue;} Set{stringvalue =value;} }    }}

2) Service1.cs (Service implementation)

Implements the method and data structure of the protocol definition.

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Runtime.Serialization;usingSystem.ServiceModel;usingSystem.Text;namespacesecondwcfsample{//Note: Using the rename command on the Refactor menu, you can change the class name "Service1" in code and configuration files at the same time.      Public classService1:iservice1 { Public stringGetData (intvalue) {            return string. Format ("You entered: {0}", value); }         Publiccompositetype getdatausingdatacontract (Compositetype composite) {if(Composite = =NULL)            {                Throw NewArgumentNullException ("Composite"); }            if(composite. Boolvalue) {composite. StringValue+="Suffix"; }            returnComposite; }    }}

3) app. Config (configuration)

Define Host,endpoint, we need to carefully read the configuration file structure, as well as notes, in the future development of the system will definitely use.

<?xml version="1.0"encoding="Utf-8"?><configuration> <system.web> <compilation debug="true"/> </system.web> <!--When you deploy a service library project, you must add the contents of the configuration file to the Host App. Config file. System.Configuration does not support the library's configuration file. -<system.serviceModel> <services> <service name="Secondwcfsample.service1"> "http://localhost:8732/Design_Time_Addresses/SecondWCFSample/Service1/"/> </baseAddresses> ""binding="Wshttpbinding"contract="Secondwcfsample.iservice1"> <!--at deployment time, the following identity elements should be removed or replaced to reflect the identity used to run the deployed service.          After deletion, WCF automatically infers the identity. -<identity> <dns value="localhost"/> </identity> </endpoint> <!--Metadata Endpoints--<!--metadata Exchange endpoint For the appropriate service to introduce itself to the client. -<!--This endpoint does not use a secure binding, you should ensure it is secure or removed before deployment-<endpoint address="Mex"binding="mexhttpbinding"contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior&gt          ; <!--to avoid leaking metadata information, set the following values before deployment tofalseand delete the above metadata end point--<servicemetadata httpgetenabled="True"/> <!--to receive fault exception details for debugging, set the following values totrue。 Before deployment, set tofalseto avoid leaking exception information-<servicedebug includeexceptiondetailinfaults="False"/> </behavior> </serviceBehaviors> </behaviors> </system.servicemodel></conf Iguration>
3. Test run

You can see the WCF test client directly with this project as the startup Project.

We can see the WCF test client, including the specific protocol. Then we click on an action, we can see the request parameter list, fill in the appropriate values, click on the call, you can see the final result of the operation

4, increase the method

Add a method to a future contract HelloWorld

The code is as follows:

[ServiceContract (namespace="http://wcf.yank.com", name="Service1", protectionlevel=protectionlevel.encryptandsign)] Public InterfaceIService1 {[OperationContract]stringGetData (intvalue);        [OperationContract]        Compositetype getdatausingdatacontract (Compositetype composite); stringHelloWorld (stringname); //TODO: Add your service actions here}

Implemented in the service class

 Public string HelloWorld (string  name)        {            returnstring. Format ("Hello {0},welcome to the WCF world. " , name);        }

Run directly, we will find that the test window does not see this method, for what?

Reason: The interface method does not specify [OperationContract], which is the contract identity of the operation.

We add, we can see it running. After modification:

        [OperationContract]        string HelloWorld (string name); 

Operation Result:

Other attribute tags are directly related to the service contract, as well as the question about the property label:

Http://www.cnblogs.com/yank/p/3666672.html

5. Add a new service agreement

Declaring a service contract

Copy Code using System; using System.ServiceModel; namespace secondwcfsample{    [ServiceContract]    publicinterface  icontact    {        [OperationContract]         string HelloWorld (string  name);}    }

Implementation services:

sing System; namespace secondwcfsample{    publicclass  contact:icontact    {        public string HelloWorld (string  name)        {            returnstring. Format ("Hello {0},welcome to the WCF world. " , name);     }}}

Configure the service:

Add a new service under the Services node

<service name="secondwcfsample.contact"> "http://localhost:8732/Design_Time_Addresses/SecondWCFSample/Contact/"/> </baseAddresses> ""binding="Wshttpbinding"contract="secondwcfsample.icontact"> <!--at deployment time, the following identity elements should be removed or replaced to reflect the identity used to run the deployed service.          After deletion, WCF automatically infers the identity. -<identity> <dns value="localhost"/> </identity> </endpoint> <!--Metadata Endpoints--<!--metadata Exchange endpoint For the appropriate service to introduce itself to the client. -<!--This endpoint does not use a secure binding, you should ensure it is secure or removed before deployment-<endpoint address="Mex"binding="mexhttpbinding"contract="IMetadataExchange"/> </service>

Operation Result:

6. Source Address

Click to download

about how to write a configuration file, here is not the introduction, specifically visible:

WCF Getting Started Tutorial (v) configuration file

Http://www.cnblogs.com/yank/p/3668371.html

WCF Getting Started Tutorial (ii) starting from scratch-creating a WCF Service

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.