我的Web API控制器中有一个POST方法,如下所示
public class StudentsController : ApiController {
public HttpResponseMessage Post(ApiStudent apiModel) {
// does processing here
}
}
public class ApiStudent {
public long Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int GraduationClass { get; set; }
// other fields omitted for brevity
}
在cilent 1中,我将ApiStudent直接添加到REST客户端的主体,这导致JSON没有转义字符。这在服务器端正确地自动反序列化,但是对于客户端2,当我使用转义字符发送JSON内容时,ApiStudent反序列化为NULL。
// DESERIALIZES PROPERLY ON SERVER
public void Client1() {
var student = new ApiStudent();
student.Id = 0; // new student since it's a post
student.FirstName = "Homer";
student.LastName = "Simpson";
student.GraduationClass = 2014;
var jsonRequest = new RestRequest("http://www.mydomain.com/api/students", Method.POST);
jsonRequest.RequestFormat = DataFormat.Json;
jsonRequest.AddBody(student);
IRestResponse jsonResponse = client.Execute(jsonRequest);
return jsonResponse;
}
// DESERIALIZES AS NULL ON SERVER
public void Client2() {
var jsonContent = "{ \"FirstName\": \"Api\", \"LastName\": \"Test\", \"GraduationClass\": 2014, \"Id\": 0 }";
var jsonRequest = new RestRequest("http://www.mydomain.com/api/students", Method.POST);
jsonRequest.RequestFormat = DataFormat.Json;
jsonRequest.AddBody(jsonContent);
IRestResponse jsonResponse = client.Execute(jsonRequest);
return jsonResponse;
}
使用fidder,我可以看到客户端1通过以下内容发送:
{ "FirstName": "Api", "LastName": "Test", "GraduationClass": 2014, "Id": 0 }
我可以看到客户端2通过以下内容发送:
{ \"FirstName\": \"Api\", \"LastName\": \"Test\", \"GraduationClass\": 2014, \"Id\": 0 }
有没有办法去除转义字符,或者在服务器端正确解析它们?
答案 0 :(得分:0)
我找到了一个解决方法,我希望它可以帮助某人。
// NOW DESERIALIZES PROPERLY ON THE SERVER
public void Client2() {
var jsonContent = "{ \"FirstName\": \"Api\", \"LastName\": \"Test\", \"GraduationClass\": 2014, \"Id\": 0 }";
var jsonRequest = new RestRequest("http://www.mydomain.com/api/students", Method.POST);
jsonRequest.AddParameter("text/json", jsonContent, ParameterType.RequestBody);
IRestResponse jsonResponse = client.Execute(jsonRequest);
return jsonResponse;
}