1

Simple requirement . I have a class - User - {userId, userName, age}.

How to serailize a object of the class and sent to a url (using post) using webclient.

Something Like below.

What is the best way to serialise user object into postdata format.

WebClient client = new WebClient();
        client.Encoding = System.Text.Encoding.UTF8;
        client.Credentials = CredentialCache.DefaultNetworkCredentials;
        string postData = "orderId=5&status=processed2&advertId=ADV0001a";
        byte[] postArray = Encoding.ASCII.GetBytes(postData);
        client.Headers.Add("Content-Type","application/x-www-form-urlencoded");
        byte[] responseArray = client.UploadData(address, postArray);
        var result = Encoding.ASCII.GetString(responseArray);
        return result;
Sumanta
  • 1,165
  • 4
  • 15
  • 25

1 Answers1

0

I would apply the following simplification to your code:

using (var client = new WebClient())
{
    client.Credentials = CredentialCache.DefaultNetworkCredentials;
    var data = new NameValueCollection 
    {
        { "userId", user.Id },
        { "userName", user.Name },
        { "age", user.Age }
    };
    var responseArray = client.UploadValues(address, data);
    return Encoding.ASCII.GetString(responseArray);
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928