locked
How to make a web api method an async method RRS feed

  • Question

  • User-740766282 posted

    I am new to Web API. I have wrote a web api method which calls a HttpWebRequest. I access this web api method through Jquery ajax async call. Problem is that, jquery ajax call doesn't wait for the response to come and throws an error. If i set ajax param async:false, then it works fine but hangs the screen till it gets the response.

    I need help in making it complete async call.

    C# Code

    [HttpGet]
            public JObject GetAvailability(string tripdetails, string bookingtype)
            {
                try
                {
                    List<TripDetails> listTripDetails = new List<TripDetails>();
                    listTripDetails = JsonConvert.DeserializeObject<List<TripDetails>>(tripdetails);
    
                    Availability objAvail = new Availability();
                    objAvail.AvailabilityInput.BookingType = bookingtype;
                    objAvail.AvailabilityInput.JourneyDetails = listTripDetails;
    
                    var jsonString = JsonConvert.SerializeObject(objAvail);
                    var result = ApiCall.Request(jsonString, "GetAvailability");
                    return JObject.Parse(result);
                  
                }
                catch(Exception ex)
                {
                    return JObject.Parse("{'error':'Message'}");
                }
            }
            
            
            public class ApiCall
    {
              public static string Request(string jsonInput,string methodName)
        {
            HttpWebRequest request = CreateWebRequest(methodName);
         
            byte[] postBytes = Encoding.UTF8.GetBytes(jsonInput);
            Stream requestStream = request.GetRequestStream();
            // now send it             
            requestStream.Write(postBytes, 0, postBytes.Length);
            requestStream.Close();
          
            using (WebResponse response = request.GetResponse())
            {
                using (StreamReader rd = new StreamReader(response.GetResponseStream()))
                {
                    string soapResult = rd.ReadToEnd();
                    return soapResult;
                }
            }
    
        }
        
         private static HttpWebRequest CreateWebRequest(string methodName)
        {
            HttpWebRequest webRequest =        (HttpWebRequest)WebRequest.Create(@"http://Somedomain/" + methodName);
            webRequest.ContentType = "application/json";
            webRequest.Method = "POST";
            return webRequest;
        }
        }

    Following is the Jquery ajax Call

    function getAvailability() {
    
                    var list = [
            { Origin: 'BOM', Destination: 'DEL', TravelDate: '12/26/2017' },
                    ];
    
                    $.ajax({
                        url: "/api/flight/Availability",
                        type: "get", //send it through get method
                        data: {
                            BookingType: "O",
                            TripDetails: JSON.stringify(list),
                        },
                        success: function (response) {
                            var res = response;
                            //Do Something
                        },
                        error: function (xhr) {
                            var err = xhr;
                            //Do Something to handle error
                        }
                    });
                };

    Thursday, July 20, 2017 6:20 AM

All replies

  • User1120430333 posted

    success: function (response)

    {

         var res = response; //Do Something

    }

    You can do anything you want on the successful path, like call a JavaScript function you made to process/do something on the successful path.

    It's either that or make a call from something that consumes the WebAPI  calls it synchronously from C# or VB.net code. 

    Thursday, July 20, 2017 12:37 PM
  • User-474980206 posted

    whether the webapi action method is async or not, makes no difference to the ajax call. the ajax call is a still a request/response. you make an webapi action async, to improve server scaling.

    Thursday, July 20, 2017 7:52 PM
  • User1168443798 posted

    Hi chandan777,

    >> Problem is that, jquery ajax call doesn't wait for the response to come and throws an error

    What error did you get?

    Based on your description, it seems your rest operation after ajax request needs the result from web api request. Is there any other code in getAvailability() function? You need to place the code which deal with the result from ajax request in success function.

    If you fail to make it work, I think you could share us a simple demo which could reproduce your issue.

    Best Regards,

    Edward

    Friday, July 21, 2017 6:47 AM
  • User753101303 posted

    Rather than "throws an error" tell which error you have. I see an extra comma (in your data)and the problem might be irrelevant to what you think. As pointed already you do have async client and server side but they are unrelated and any combination should work.

    Not directly related but I would suggest to always try to take advantage of what ASP.NET offer ie here you are writing your own explicit serializatin code while ASP.NET does it for you (and you can even request json or xml at will). 

    Friday, July 21, 2017 5:29 PM