Wednesday 31 August 2011

Output JSON from WCF RESTful Web Service


Under Microsoft WCF 4 framework, output either XML or JSON is fairly straightforward by simply setting a proper attribute property in your public service API function.

 
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class MyWebService
{
   [OperationContract]
   [WebGet(UriTemplate = "MyWebFunction/{userReq}", 
           ResponseFormat = WebMessageFormat.Json )]
   public string MyWebFunction(string userReq)
   {
      // do your magic here
      return "your magic result";
   }
   
   // your other public web function(s)
}
 

No comments:

Post a Comment