简体   繁体   中英

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\": \"admin@admin.com\",\"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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM