I am trying to send a PUT request to update some data. In Fiddler in the Inspectors > Text View the data is shown as following :
"{\"site\":[{\"technologyId\":1,\"isActive\":1},{\"technologyId\":2,\"isActive\":1},{\"technologyId\":3,\"isActive\":1},{\"technologyId\":4,\"isActive\":1}]}"
If I open the jsonData in TextViewer while debugging it shows the following:
{"site":[{"technologyId":1,"isActive":1},{"technologyId":2,"isActive":1},{"technologyId":3,"isActive":1},{"technologyId":4,"isActive":1}]}
I thought this is what is passed to the server when I passed jsonData in PutAsJsonAsync.
In fiddler the response comes back as 500 Internal Server Error and if I click on TextView it shows {"error":"Error: invalid json"}
. To my understanding the \
is escape character for "
in C# and should not be passed. I am not sure how to resolve this
static void Main()
{
RunAsync().Wait();
}
static async Task RunAsync()
{
using (var client = new HttpClient())
{
Uri siteTechUpdateUrl = new Uri("http://xyz/api/1234");
// HTTP PUT
// Update site# 16839 Technologies
var collection = new List<SiteTechnology>();
collection.Add(new SiteTechnology() { technologyId = 1, isActive = 1 });
collection.Add(new SiteTechnology() { technologyId = 2, isActive = 1 });
collection.Add(new SiteTechnology() { technologyId = 3, isActive = 1 });
collection.Add(new SiteTechnology() { technologyId = 4, isActive = 1 });
dynamic siteTechs= new
{
site = collection
};
string jsonData = JsonConvert.SerializeObject(siteTechs);
// jsonData value "{\"site\":[{\"technologyId\":1,\"isActive\":1},{\"technologyId\":2,\"isActive\":1},{\"technologyId\":3,\"isActive\":1},{\"technologyId\":4,\"isActive\":1}]}"
HttpResponseMessage response2 = await client.PutAsJsonAsync(siteTechUpdateUrl, jsonData);
if (response2.IsSuccessStatusCode)
{
Console.ReadLine();
}
}
}
class SiteTechnology
{
public int technologyId;
public int isActive;
}
You're serializing it to a string, and then sending the string as JSON.
Instead of:
client.PutAsJsonAsync(siteTechUpdateUrl, jsonData);
try:
client.PutAsJsonAsync(siteTechUpdateUrl, siteTechs);