If you are new to WCF Service, please read my earlier blogs. WCF Introduction and WCF Contracts
As we know the default message protocol in WCF is SOAP. Message contract is used to define the SOAP structure. As we know SOAP has Envelope, Header, and Body. So if you want control over SOAP then you must use Message Contract.
First, let’s see Data Contract Request and Response. Know more about Data Contract in WCF
[ServiceContract] public interface IProductService { [OperationContract] Product GetProduct(int ProductID); } [DataContract] public class Product { [DataMember] public int ProductID { get;set; } [DataMember] public string ProductName { get;set; } [DataMember] public string ProductSeller { get;set; } public decimal ProductCost { get;set; } } |
Service Implementation
public Product GetProduct(int ProductID) { Product objProduct = new Product(); objProduct.ProductID = 10; objProduct.ProductName = “Laptop”; objProduct.ProductCost = 40000; objProduct.ProductSeller = “XYZ Seller”; return objProduct; } |
You can see ProductID, ProductName and ProductSeller are only visible in Response why because we have not added DataMemeber attribute to ProductCost
How to implement Message Contract in WCF:
[ServiceContract] public interface IProductService { [OperationContract] [FaultContract(typeof(string))] ProductResponse GetInfo(ProductRequest Req); } [MessageContract] public class ProductRequest { [MessageHeader] public string PId; } [MessageContract] public class ProductResponse { [MessageBodyMember] public Product prdObj; } [DataContract] public class Product { [DataMember] public string ProductName { get; set;} [DataMember] public string SellerName { get; set; } [DataMember] public decimal Cost { get; set; } } |
Service Implementation:
public ProductResponse GetInfo(ProductRequest Req) { if (Req.PId != “P1”) { string x = “No Product exist with this ID”; throw new FaultException<string>(x); } ProductResponse res = new ProductResponse(); res.prdObj = new Product(); // create an object of Auther Class res.prdObj.ProductName = “Laptop”; res.prdObj.SellerName = “XYZ Company”; res.prdObj.Cost = 40000; return res; } |
In above example, I have assumed default product id is P1
Now, run the service and see SOAP format below. You may notice Product Id P1 in header and Product Request in SOAP body section.
In response, you may notice Product Response in SOAP body section.
Related blogs to WCF Service-
- Introduction to WCF
- ABC of WCF
- Basics of WCF Architecture
- WCF vs Web Service
- What is XML serialization?
- WCF Binding
- Create first WCF application
- Fault Contract in
- WCF Data Contract vs Message Contract
- Message Contract
- Data Contract Serialization and De-Serialization
- Data Contract in WCF
- Operation Contract in WCF
- Service Contract in WCF
- How to host a WCF service in IIS?
- WAS Hosting in WCF
- Self Hosting in WCF
- How to create WCF RESTful Service.