locked
Call web Api from another Web Api RRS feed

  • Question

  • User126413593 posted

    Hi I have two web api that work in series, the first web api post a list to the second for some process after that the second web api send back the search result to the first

    I receive the list in second web api and process it successfully but I cant get the result in first web api. I replaced the first web api with console application and it worked properly but it not work with web api !

    This is my first Web api code and I want the result in my amadeus variable

            static async Task CallWebApiAsync(List<ReqInfo> reqInfo)
            {
                SearcheResultId amadeus = new SearcheResultId();
                using (var client = new HttpClient())
                {
                    //Amadeus
                    client.BaseAddress = new Uri("http://localhost:21879/");
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    //POST Method
                    HttpResponseMessage responsePostA = await client.PostAsJsonAsync("api/Amadeus/SearchFlight", reqInfo);
    
                    if (responsePostA.IsSuccessStatusCode)
                    {
                        amadeus = await responsePostA.Content.ReadAsAsync<SearcheResultId>();
                        // Get the URI of the created resource.
                        Uri returnUrl = responsePostA.Headers.Location;
                        Console.WriteLine(returnUrl);
                    }
    
                }
            }

    and this is my second web api code

            [Route("api/Amadeus/SearchFlight")]
            public SearcheResultId PostFlights([FromBody] List<ReqInfo> reqInfo)
            {
                return resultTwoWay;
            }

    Could you please help me to find what is the problem !?

    Saturday, February 25, 2017 7:55 AM

All replies

  • User753101303 posted

    Hi,

    Please always describe what happens rather than just telling that "it doesn't work". Even for few lines of code there is sometimes quite few things that could be wrong (and not only because of the code that is shown).

    For example here your PostFlights method have just one line and retuns something declared elsewhere and I have no idea how it is populated. Could it be that your PostFlights call just return null ??? Do you enter the if block in the first API Call? If yes what is the value of your amadeus variable? (null ?) Or do you have just an error message without even telling about it ??? Fianlly it seems weird you don"t even return anything form the 1st web api call.

    For web APIs try to use stateless calls.ie you should avoid to return something that depends on some previous state that has been set maybe from a previous call ???

    Saturday, February 25, 2017 9:02 AM
  • User126413593 posted

    Dear Patrice

    My second Web api work properly and this the code

    [Route("api/Amadeus/SearchFlight")] 
    public SearcheResultId PostFlights([FromBody] List<ReqInfo> reqInfo)
            {
                
                    MultiDestination4 obj = new MultiDestination4();
    
                    result = obj.MultipleFlight(reqInfo);
                    SearcheResultId finalResult = new SearcheResultId()
                    {
                        SessionId = (string)HttpContext.Current.Session["fd"],
                        Result = result
                    };
                    return finalResult;
               
            }

     and after I send reqInfo list to second web api from the first the result calculated correctly but when it return I cant receive in my first web Api

    I don't have any error message and right now I am testing the and it doesn't require any return.

    Tnx

    Saturday, February 25, 2017 9:13 AM
  • User-2057865890 posted

    Hi AaronSwartz,

    The above code should work, you could refer this.

    Html

    <!DOCTYPE html>
    <html>
    <head>
        <title></title>
        <meta charset="utf-8" />
        <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    </head>
    <body>
    
    </body>
    </html>
    <script>
        $(document).ready(function () {
            var reqInfo = [
                { ReqId: 1 },
                { ReqId: 2 },
                { ReqId: 3 }
            ];
    
            reqInfo = JSON.stringify(reqInfo);
    
            $.ajax({
                type: 'POST',
                url: 'api/Amadeus/CallWebApiAsync',
                data: reqInfo,
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function () {
                    alert('successfully called.');
                },
                failure: function (response) {
    
                }
            });
        });
    </script>
    

    API

    public class AmadeusController : ApiController
        {
            [Route("api/Amadeus/CallWebApiAsync")]
            public async Task CallWebApiAsync([FromBody]List<ReqInfo> reqInfo)
            {
                SearcheResultId amadeus = new SearcheResultId();
                using (var client = new HttpClient())
                {
                    //Amadeus
                    client.BaseAddress = new Uri("http://localhost:64743/"); //change
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    //POST Method
                    HttpResponseMessage responsePostA = await client.PostAsJsonAsync("api/Amadeus/SearchFlight", reqInfo);
    
                    if (responsePostA.IsSuccessStatusCode)
                    {
                        amadeus = await responsePostA.Content.ReadAsAsync<SearcheResultId>();
                        // Get the URI of the created resource.
                        Uri returnUrl = responsePostA.Headers.Location;
                        //  Console.WriteLine(returnUrl);
                    }
                }
            }
    
            [Route("api/Amadeus/SearchFlight")]
            public SearcheResultId PostFlights([FromBody] List<ReqInfo> reqInfo)
            {
                SearcheResultId finalResult = new SearcheResultId()
                {
                    SessionId = "test"
                };
                return finalResult;
            }
    
        }

    Model

    public class ReqInfo
    {
       public int ReqId { get; set; }
    }

    Best Regards,

    Chris

    Tuesday, March 7, 2017 6:59 AM