我正在尝试发送PUT请求来更新一些数据。在检查员的Fiddler>文本查看数据显示如下:
"{\"site\":[{\"technologyId\":1,\"isActive\":1},{\"technologyId\":2,\"isActive\":1},{\"technologyId\":3,\"isActive\":1},{\"technologyId\":4,\"isActive\":1}]}"
如果我在调试时在TextViewer中打开jsonData,则会显示以下内容:
{"site":[{"technologyId":1,"isActive":1},{"technologyId":2,"isActive":1},{"technologyId":3,"isActive":1},{"technologyId":4,"isActive":1}]}
我认为这是在PutAsJsonAsync中传递jsonData时传递给服务器的内容。
在fiddler中,响应以500内部服务器错误的形式返回,如果我单击TextView,则会显示{"error":"Error: invalid json"}
。据我所知,\
是C#中"
的转义字符,不应传递。我不知道如何解决这个问题
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;
}
答案 0 :(得分:2)
您将其序列化为字符串,然后将字符串作为JSON发送。
而不是:
client.PutAsJsonAsync(siteTechUpdateUrl, jsonData);
尝试:
client.PutAsJsonAsync(siteTechUpdateUrl, siteTechs);