Search code examples
c#asp.netresthttpwebrequest

How to pass an object as a parameter in HttpWebRequest POST?


Here I am calling Restful WCF service from my web application and I don't know how to pass an object as parameter in this one. Here is my client code:

protected void Button1_Click(object sender, EventArgs e)
{
    UserInputParameters stdObj = new UserInputParameters
    {
        AssociateRefId = "323",
        CpecialLoginId = "a@gmail.com",
        PartnerId = "aaaa",
        FirstName = "aaaa",
        LastName = "bbbb",
        Comments = "dsada",
        CreatedDate = "2013-02-25 15:25:47.077",
        Token = "asdadsadasd"
    };

    string url = "http://localhost:13384/LinkService.svc/TokenInsertion";

    try
    {
        ASCIIEncoding encoding = new ASCIIEncoding();
        System.Net.WebRequest webReq = System.Net.WebRequest.Create(url);
        webReq.Method = "POST";
        webReq.ContentType = "application/json; charset=utf-8";
        DataContractJsonSerializer ser = new DataContractJsonSerializer(stdObj.GetType());
        StreamWriter writer = new StreamWriter(webReq.GetRequestStream());
        writer.Close();
        webReq.Headers.Add("URL", "http://localhost:13381/IntegrationCheck/Default.aspx");
        System.Net.WebResponse webResp = webReq.GetResponse();
        System.IO.StreamReader sr = new System.IO.StreamReader(webResp.GetResponseStream());
        string s = sr.ReadToEnd().Trim();
    }
    catch (Exception ex)
    {
    }
}

And my service method:

  public string UserdetailInsertion(UserInputParameters userInput)

Solution

  • You have to parse the object in the format and write it into the RequestStream.

    Your class

    [Serializable]
    class UserInputParameters {
        "your properties etc"
    };
    

    The code to serialize the object

    private void SendData(UserInputParameters stdObj) {
        DataContractJsonSerializer ser = new DataContractJsonSerializer(stdObj.GetType());
        StreamWriter writer = new StreamWriter(webReq.GetRequestStream());
        JavaScriptSerializer jss = new JavaScriptSerializer();
    
        // string yourdata = jss.Deserialize<UserInputParameters>(stdObj);
        string yourdata = jss.Serialize(stdObj);
        writer.Write(yourdata);
        writer.Close();
    }
    

    This should be the trick.

    The class JavaScriptSerializer is located in the namespace System.Web.Script.Serialization which can be found in the assembly System.Web.Extensions (in System.Web.Extensions.dll) here is the MSDN Article: http://msdn.microsoft.com/en-us/library/bb337131.aspx