In the previous article and you reviewed some of the basics of WCF, this article through an example and share how to develop a GET, add student information WCF service.
The following tasks are involved in developing the endpoints of WCF services:
Development Service Contract: Specifies the operation of the WCF service available to the endpoint.
Development bindings: Binds the protocol that directs the endpoint to communicate with the outside world.
Add, delete, update, and configure endpoints: Add and bind endpoints in configuration files (which can also be encoded in the form of, but not recommended). )
Add behavior: An action is a component that enhances the run-time behavior of services, endpoints, and operations.
Develop a WCF service contract
A WCF service contract is decorated with a metadata attribute [ServiceContract]. NET interface or class. Each WCF service can have one or more contracts, each of which is a collection of operations.
First we define a. NET interface: Istuservicecontract, defines two methods to implement the function of adding and acquiring student information separately
void AddStudent(Student stu);stuCollection GetStudent();
Using the metadata attribute of WCF service Model ServiceContract annotation Interface Istuservicecontract, the interface is designed as WCF contract. Mark Addstudent,getstudent with OperationContract
Getstudent () Returns a collection of type stucollection types. Addstudent () needs to pass in the student entity class as an argument.
Namespace Wcfstudent
{
[ServiceContract]
public interface Istuservicecontract
{
[OperationContract]
void Addstudent (Student stu);
[OperationContract]
Stucollection getstudent ();
}
[DataContract]
public class Student
{
private string _stuname;
private string _stusex;
private string _stuschool;
[DataMember]
public string Stuname
{
get {return _stuname;}
set {_stuname = value;}
}
[DataMember]
public string Stusex
{
get {return _stusex;}
set {_stusex = value;}
}
[DataMember]
public string Stuschool
{
get {return _stuschool;}
set {_stuschool = value;}
}
}
public class Stucollection:list<student>
{
}
}
The WCF service and the customer Exchange soap information. At the sender end, the data of the WCF service and customer interaction must be serialized into XML and the XML drag at the receiving end. Therefore, the student object that the customer passes to the addstudent operation must also be serialized to XML before being sent to the server. WCF defaults to an XML serializer DataContractSerializer, which uses it to serialize and drag the data exchanged by WCF services and customers.
As a developer, what we have to do is to use metadata attribute DataContract to annotate the types of data that WCF and its customers exchange. DataMember the attributes to be serialized in the interchange data type with the metadata attribute. (see above code in detail)