这是我的Api Controlller方法,它正在与Rest api Url交谈。我正在发送所有必要的数据来搜索此url.Now,一切正常,它返回Http状态代码200并带有适当的响应。示例代码为:
[System.Web.Http.HttpPost]
public async Task<HttpResponseMessage> SearchFlight([FromBody]SearchForFlight sof)
{
string url = "http://api.tektravels.com/BookingEngineService_Air/AirService.svc/rest/Search/";
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new
System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var payload = JsonConvert.SerializeObject(sof);
var response = await client.PostAsync(url, new StringContent(payload, Encoding.UTF8, "application/json"));
var json = await response.Content.ReadAsStringAsync();
HttpResponseMessage res = Request.CreateResponse(HttpStatusCode.OK, json);
return res;
}
}
我正在序列化sof对象并回发到客户端对象:
var response = await client.PostAsync(url, new StringContent(payload, Encoding.UTF8, "application/json"));
现在,如果我尝试使用以下方法从此响应中读取字符串形式的内容:
var json = await response.Content.ReadAsStringAsync();
现在,我在这里得不到适当的回应。我得到的回应是:
"{\"Response\":{\"ResponseStatus\":3,
\"Error\":{\"ErrorCode\":3,\"ErrorMessage\":\"Please specify Flight Segment.\"},
\"TraceId\":\"98b33a39-5dd9-48fa-999c-0eb5c99adef1\"}}"
问题就在这里。 根据文档,Segment对象应该是这样的:
"Segments": [
{
"Origin": "DEL",
"Destination": "BOM",
"FlightCabinClass": "1",
"PreferredDepartureTime": "2015-11-06T00: 00: 00",
"PreferredArrivalTime": "2015-11-06T00: 00: 00"
}
],
当我使用此代码将数据发送回web api控制器时。这里我省略了来自Segments对象的[]数组符号。
<script>
$(document).ready(function () {
$("#btnPost").click(function () {
var sof = {
AdultCount: $("#AdultCount").val(),
JourneyType: $("#JourneyType :selected").text(),
PreferredAirlines: null,
Segments: {
Origin: $("#Origin").val(),
Destination: $("#Destination").val(),
FlightCabinClass: $("#FlightCabinClass").val(),
PreferredDepartureTime: $("#PreferredDepartureTime").val(),
PreferredArrivalTime: $("#PreferredArrivalTime").val(),
},
};
如果我没有省略这个[]数组符号,那么我就无法将适当的数据发回 web api controller。如果我省略,那么我收到错误的回应。 how to assign values to nested object through json object array我被告知要忽略这个问题。 请有人帮助我。
答案 0 :(得分:0)
在SearchForFlight类中,将Segments属性设为列表。
public List<otherType> Segments { get; set; }
在你的js中,使用数组
Segments: [
{
Origin: $("#Origin").val(),
Destination: $("#Destination").val(),
FlightCabinClass: $("#FlightCabinClass").val(),
PreferredDepartureTime: $("#PreferredDepartureTime").val(),
PreferredArrivalTime: $("#PreferredArrivalTime").val(),
}
]