0

This is my Api Controlller Method which is talking to a Rest api Url.I am sending all the necessary data to do a search on this url.Now, Everything is Ok and it returns back Http Status Code 200 with proper Response.The Sample code is:

   [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;
       }
    }

I am serializing the sof object and posting back to client object:

 var response = await client.PostAsync(url, new StringContent(payload, Encoding.UTF8, "application/json"));

Now, If i try to read the content in string form from this response using this:

  var json = await response.Content.ReadAsStringAsync();

Now, here i am not getting proper Response. The Response i get back is:

"{\"Response\":{\"ResponseStatus\":3, 
 \"Error\":{\"ErrorCode\":3,\"ErrorMessage\":\"Please specify Flight Segment.\"},
\"TraceId\":\"98b33a39-5dd9-48fa-999c-0eb5c99adef1\"}}"

The Problem is here. According to documentation, Segment object should be something like this:

"Segments": [
             {
              "Origin": "DEL",
              "Destination": "BOM",
              "FlightCabinClass": "1",
              "PreferredDepartureTime": "2015-11-06T00: 00: 00",
              "PreferredArrivalTime": "2015-11-06T00: 00: 00"
             }
            ],

While i am sending back data to web api controller using this code.Here i have omitted []array symbol from Segments object.

  <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(),
                        },
                };

If i did not omit this []array symbol, then i cant post back proper data to web api controller.If I omit then i am getting error in response. how to assign values to nested object through json object array I was told to omit as u can see in this question. Please some one help me.

Community
  • 1
  • 1
duke
  • 1,816
  • 2
  • 18
  • 32
  • how does `SearchForFlight` class look like? can you share the code. if `Segments` is an array, you'll need to send an array. – Amit Kumar Ghosh May 18 '16 at 09:01
  • @AmitKumarGhosh u can see sample code here http://pastebin.com/ZCPVehqK – duke May 18 '16 at 09:16
  • According to documentation, use see array? then the properties of the class SearchForFlight you created is not matching with the class SearchForFlight defined in the Rest api Url. can you verify it once – Karthik M R May 18 '16 at 10:24
  • I have created SearchForFlight class by myself there is only problem with [] array litrals, if i could include them by anyway then everything would work fine @KarthikMR – duke May 18 '16 at 10:27
  • you have created the class SearchForFlight. But the api you are calling /rest/search expects SearchForFlight parameter. So, here this class has List of Segments. Can you check the properties in that api – Karthik M R May 18 '16 at 10:37
  • okk may be u r right...The Url for Search simply wants json array like this--http://pastebin.com/seVhZKpy so, i am sending those through jquery post method and retreiving them on web api like this---public async Task SearchFlight([FromBody]SearchForFlight sof) .Now,If u can provide me any way. Just [ this symbol is main problem. hope u understand @KarthikMR – duke May 18 '16 at 10:49
  • have posted an answer to accommodate the changes. Can't the class in the api side be changed?Don't you have control ? – Karthik M R May 18 '16 at 11:18

1 Answers1

0

In your SearchForFlight class, make Segments property a list.

 public List<otherType> Segments { get; set; }

In your js, use array

 Segments: [
             {
                Origin: $("#Origin").val(),
                Destination: $("#Destination").val(),
                FlightCabinClass: $("#FlightCabinClass").val(),
                PreferredDepartureTime: $("#PreferredDepartureTime").val(),
                PreferredArrivalTime: $("#PreferredArrivalTime").val(),
              }
           ]
Karthik M R
  • 980
  • 1
  • 7
  • 12
  • Error at this line @Html.LabelFor(model => model.Segments.Origin, htmlAttributes: new { @class = "control-label col-md-2" }) 'System.Collections.Generic.List' does not contain a definition for 'Origin' and no extension method 'Origin' accepting a first argument of type 'System.Collections.Generic.List' could be found – duke May 18 '16 at 11:29
  • use this - @Html.LabelFor(model => model.Segments[0].Origin, htmlAttributes: new { @class = "control-label col-md-2" }) – Karthik M R May 18 '16 at 11:34
  • System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection at the same line after using @Html.LabelFor(model => model.Segments[0].Origin, – duke May 18 '16 at 11:39
  • Is your Model in the view has values? – Karthik M R May 18 '16 at 11:48
  • My model initially dont have any values – duke May 18 '16 at 11:54
  • In your constructor , add list - public SearchForFlight() { JourneyList = new List(); FlightCabinClassList = new List(); Segments = new List(); } – Karthik M R May 18 '16 at 11:55
  • added already @Karthik – duke May 18 '16 at 11:59
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/112286/discussion-between-karthik-m-r-and-duke). – Karthik M R May 18 '16 at 12:06