HTTP Post from SilverLight application to a REST Service

0 comments

Objective:
  1. How to create REST service for JSON request and response format.
  2. How to create SilverLight Client, which will consume a REST service on JSON data format.
  3. How to POST data in JSON format from SilverLight client.
Pre Requisite

Reader should have basic knowledge of REST services. For more on REST read my other articles.

For Solution follow below steps:
Step 1:

Create new WCF Service Application

File -> New -> Project -> Web -> WCF Service Application
WCFService1.gif

Solution explorer would like more or less,

WCFService2.gif

Step 2:
Remove all the default code in service1.svc and IService1.cs.
Paste the below code there in IService1.cs .

Note :
  1. If you have changed the name of service interface then take care of that. If you have changed IService1 to ITest then update code in ITest.cs. if you have changed name of Service1.cs then update code in changed class.
     
  2. In this sample, adding object of Test class in a static list and fetching it back. If you want to perform pure Data base operation (CRUD). Just replace Insert code and get Code with your database operation code.
     
  3. Add reference of System.ServiceModel.Web to IService1.cs.
     
  4. Now what is Test class here? And where it should be declared and created. So just right click on service project and add a class. Give name of the classTest and paste below code over there.
Test.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SilverLightRestTesting
{
    public class Test    {
        public int Marks { getset; }
        public String Name { getset; }
    }
}

IService1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
namespace SilverLightRestTesting
{
    // NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in Web.config.    [ServiceContract]
    public interface IService1    {
[OperationContract]        [WebGet(UriTemplate="/Data",BodyStyle=WebMessageBodyStyle.Bare,RequestFormat=WebMessageFormat.Json,ResponseFormat=WebMessageFormat.Json)]
List<Test> GetTest();
[OperationContract]
[WebInvoke(UriTemplate = "/Data", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat =WebMessageFormat.Json)]
void InsertTest(Test t);
    }
}

READ MORE>>

0 comments: