miniHessel
miniHessel

Reputation: 846

How to serialize Json object into System.Net.WebClient (.NET 3.5)

How can you serialize a json object and pass it on to an api call, like the one in the example posted as an answer here Call web APIs in C# using .NET framework 3.5

System.Net.WebClient client = new System.Net.WebClient();
 client.Headers.Add("content-type", "application/json");//set your header here, you can add multiple headers
 string s = Encoding.ASCII.GetString(client.UploadData("http://localhost:1111/Service.svc/SignIn", "POST", Encoding.Default.GetBytes("{\"EmailId\": \"[email protected]\",\"Password\": \"pass#123\"}")));

In Postman I would just do this

 var client = new RestClient("");
 var request = new RestRequest(Method.POST);
 request.JsonSerializer = new RestSharpJsonNetSerializer();
 request.AddJsonBody(JsonObject);

However, as Postman is not supported in .net framework 3.5, I have to use System.Net.WebClient.

Upvotes: 0

Views: 2479

Answers (1)

Evk
Evk

Reputation: 101473

You can do what you want with WebClient (and Json.NET package) like this:

var yourObject = new YourObject {
    Email = "email",
    Password = "password"
};
string s = client.UploadString("http://localhost:1111/Service.svc/SignIn","POST", JsonConvert.SerializeObject(yourObject));

Upvotes: 1

Related Questions