我将数据从一个dto绑定到另一个,以便能够在c#中的post方法中使用Rest客户端发送json数据请求。 当我将数据从一个dto绑定到另一个时,最终的dto(将用于发送请求)必须为json格式,但我注意到在发送请求之前,我的数据中已添加了自动生成的ID 。发送请求后,我收到错误代码400 Bad Request,当我手动删除请求数据中的自动生成的ID并发送请求后,一切正常。没有这些自动生成的ID如何发送json数据?
这是我的代码:
using (HttpClient client = new HttpClient())
{
try
{
if (!datarequest.IsNull())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("userName", "".AppendWebConfigValue("Username"));
client.DefaultRequestHeaders.Add("password", "".AppendWebConfigValue("Password"));
我尝试同时使用ToJSONString()和SerializeObject()
//string jsonObjectA = datarequest.ToJSONString();
string jsonObjectA = JsonConvert.SerializeObject(datarequest);
HttpContent content = new StringContent(jsonObjectA, Encoding.UTF8, "application/json");
// Add an Accept header for JSON format.
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.BaseAddress = new Uri("https://localhost:20458");
httpResponse = client.PostAsync("/method/test", content).Result;
if (!httpResponse.IsNull())
respDto = httpResponse.Content.ReadAsAsync<dataResponseDto>().Result;
生成的dto,它在包含自动生成的ID的请求中发送给它:
{"$id":"1","Type":"Initiate","Persons":[{"$id":"2","Name":
{"$id":"3","FirstName":"John","LastName":"Doe"},"SSN":
{"$id":"4","Number":"21790####","Type":"ssn9"},"Phones":
[{"$id":"5","Number":"5615555555","Context":"mobile"}]}]}
如何删除这些"$id":"1"
和"$id":"2"
...以请求的格式发送数据?