简体   繁体   中英

How to call a WCF method asynchronously from MVC4 WebAPI

I am new to the WebApi, .Net world and am totally confused with all the information available as to what approach I should take. I have created a WebService using MVC4 WebApi that Twilio calls when a text message is received. I need to respond to this text message. I am consuming a WCF method which is currently being called synchronously. Since it is possible that my process can take longer than 3-5 seconds to process a reply to the text message the connection to Twilio gets disconnected due to timeout. So I am looking for ways to call this WCF method asynchronously. My question is to call the WCF method (I am calling the WCF using a Object Factory and using) do I need to update the contract to say Async? I am little confused on that.

BTW my Web Service is in IIS7 and am using .Net4.5 framework and MVC4 WebApi .

My code is somewhat like this: So I would like to call the SendSms part asynchronously. How do I do that? Can I simply use Task.Run Async and Await?

 using Twilio.Mvc;
 using Twilio.TwiML.Mvc;
 using Twilio.TwiML;


public class SmsController : ApiController
{
    [HttpPost]
    public HttpResponseMessage Post([FromBody]SmsRequest smsReq)
    {
            var response = new Twilio.TwiML.TwilioResponse();
            //validation checks..

            try
            {

                -- call to WCF to get the List of sms to be sent 
                if ((txtMessageResponse != null) && (txtMessageResponse.SmsMessageInfo.Count > 0))
                {
                    _smsStagingList = txtMessageResponse.SmsMessageInfo;
                    foreach (TextMessageStaging prepareTextMessageResponse in _smsStagingList)
                    {
                        smsDTO textMessageItems = new smsDTO();
                        textMessageItems.PhoneNumber = prepareTextMessageResponse.PhoneNumber;
                        textMessageItems.SmsMessage = prepareTextMessageResponse.SmsMessageBody;

                        isTxtMessageSent = SendSms(textMessageItems);

                        //If the messages were sent then no need to set the flag to be updated 
                        if (isTxtMessageSent)
                        {
                            txtMessageStatusToBeUpdated = false;
                        }
                    }
                    return Request.CreateResponse(HttpStatusCode.OK, twilioResponse.Element);
                }
                else
                {
                    //send error response
                }
            catch (Exception msgProcessingError)
            {
              //send error response again as processing error
            }
            finally
            {
             //set the outbound flag in the table
            }
     }


    private bool SendSms(smsDTO textMessageItems)
    {
        bool isTxtMessageSent = false;
        PushMessageRequest txtMessageRequest = new PushMessageRequest();
        PushMessageResponse txtMessageResponse = null;
        txtMessageRequest.SmsMessageInfo = new SendTextMessage(); //instantiate the dto

        txtMessageRequest.SmsMessageInfo.ToPhone = textMessageItems.PhoneNumber;
        txtMessageRequest.SmsMessageInfo.TextMessage = textMessageItems.SmsMessage;
        try
        {
            using (ITextService textService = ObjectFactory.SendSmsMessage())
            {
                txtMessageResponse = textService.SendSmsMessage(txtMessageRequest);
            }

            isTxtMessageSent = txtMessageResponse.IsSuccessful;
        }
        catch (Exception ex)
        {
            isTxtMessageSent = false;
        }      
        return isTxtMessageSent;
    }          

Twilio evangelist here.

OK, so you have a Web API method in which you call a WCF method that is potentially long running. There are two problems to solve here:

  1. How do you call the WCF method in a way that does not block the Web API method from returning a response
  2. How do you get Twilio to wait until the WCF method has finished

I wrote a blog post a while ago that shows you how to create an indefinite wait loop in an IVR by leveraging .NET's Task Parallel library and the loop attribute on Twilios <Play> verb.

The gist of the post is that you can use the TPL's StartNew method to start the long running WCF method on a new thread. This lets ASP.NET continue and lets you return some TwiML so Twilio does not end the call. Then you pair that with a continuation which lets you know when the WCF service request is done and you can signal back to Twilio using the REST API to redirect the in-progress call to a new set of TwiML instructions.

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM