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

32,666

Solution 1

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

Solution 2

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; }

        }
    }
Share:
32,666
Rooney
Author by

Rooney

Updated on June 05, 2020

Comments

  • Rooney
    Rooney almost 4 years

    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)
    
  • Knerd
    Knerd about 11 years
    You have to pass the JSON-String ;)
  • Knerd
    Knerd about 11 years
    I changed it, there are many alternatives to serialize JavaScript, but this is my favorite.
  • Rooney
    Rooney about 11 years
    am getting an error like the best overloaded method match has some invalid arguments in this line string yourdata = jss.Deserialize<UserInputParameters>(stdObj);
  • Ben Pretorius
    Ben Pretorius almost 9 years
    string yourdata = jss.Deserialize<UserInputParameters>(stdObj); should be: string yourdata = jss.Serialize(stdObj);
  • Oscar
    Oscar almost 8 years
    Where are you using the "ser" variable created with from the new DataContractJsonSerializer...???