Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 = "[email protected]",
        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)
like image 370
Rooney Avatar asked Feb 25 '13 11:02

Rooney


2 Answers

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

like image 142
Knerd Avatar answered Sep 24 '22 18:09

Knerd


We can not send an Object data to the remote server from server side code using WebRequest class in C# as we can send only stream data to the remote server and object representation in memory is not stream.Hence before sending the object we need to serialize it as a stream and then we are able to send it to the remote server.Below is the complete code.

   namespace SendData
    {
      public class SendObjectData
        {
            static void Main(string[] args)
            {

              Employee emp = new Employee();
              emp.EmpName = "Raju";
              emp.Age = 30;
              emp.Profession = "Teacher";

              POST(emp);
            }

           // This method post the object data to the specified URL.
            public static void POST(Employee objEmployee)
            {
              //Serialize the object into stream before sending it to the remote server
                MemoryStream memmoryStream = new MemoryStream();
                BinaryFormatter binayformator = new BinaryFormatter();
                binayformator.Serialize(memmoryStream, objEmployee);

              //Cretae a web request where object would be sent
                WebRequest objWebRequest = WebRequest.Create(@"http://localhost/XMLProvider/XMLProcessorHandler.ashx");
                objWebRequest.Method = "POST";
                objWebRequest.ContentLength = memmoryStream.Length;
              // Create a request stream which holds request data
                Stream reqStream = objWebRequest.GetRequestStream();
             //Write the memory stream data into stream object before send it.
                byte[] buffer = new byte[memmoryStream.Length];
                int count = memmoryStream.Read(buffer, 0, buffer.Length);
                reqStream.Write(buffer, 0, buffer.Length);

             //Send a request and wait for response.
                try
                {
                    WebResponse objResponse = objWebRequest.GetResponse();
             //Get a stream from the response.
                    Stream streamdata = objResponse.GetResponseStream();
             //read the response using streamreader class as stream is read by reader class.
                    StreamReader strReader = new StreamReader(streamdata);
                    string responseData = strReader.ReadToEnd();
                }
                catch (WebException ex) {
                    throw ex;
                }

            }
        }
   // This is an object that needs to be sent. 
        [Serializable]
        public class Employee
        {

            public string EmpName { get; set; }
            public int Age { get; set; }
            public string Profession { get; set; }

        }
    }
like image 37
Sheo Dayal Singh Avatar answered Sep 26 '22 18:09

Sheo Dayal Singh