如果不成功,则循环操作

时间:2016-04-19 14:14:10

标签: loops asp.net-mvc-4

我有代码尝试在收到成功付款后创建充值代金券代码,但由于RNSP服务器一次只能处理一个事务,我遇到了困难。我在MVC控制操作中有以下代码,如果在第一次尝试时无法创建凭证代码,那么最好循环几次到最多5次。

//Check the Realex response Code
if (tResp.ResultCode == 0)
{                    
   try
   {
      //Create the Voucher code
      ViewBag.VendCode = createVoucher(topupKeypadNumber.ToString(), topupAmount.ToString());
   }
   catch (Exception ex)
   {
      //SET THE VARIABLES TO BE DISPLAYED ON THE VEND CODE DISPLAY PAGE
      System.Diagnostics.EventLog.WriteEntry("Application", "GENERAL ERROR : " + ex.Message, System.Diagnostics.EventLogEntryType.Information);
      ViewBag.Title = "Vend Code Error";
      ViewBag.Message = "An error has occurred while retrieving your vend code. Please contact our customer service team.";
      return View("Info");
   }
   //SET THE VARIABLES TO BE DISPLAYED ON THE VEND CODE DISPLAY PAGE
   ViewBag.Title = "Issue Vend Code";
   ViewBag.Message = ViewBag.VendCode;
   return View("Success");
}

1 个答案:

答案 0 :(得分:1)

试试这个。

if (tResp.ResultCode == 0)
{    
   int maximumRetryLimit=5; 
   int retryCount=0; 
   bool isVoucherCreated;     
   try
   {
      while(retryCount<=maximumRetryLimit)
      {    //Create the Voucher code
         ViewBag.VendCode = createVoucher(topupKeypadNumber.ToString(), topupAmount.ToString());
         if(ViewBag.VendCode!=null) 
         {
            isVoucherCreated=true;
            break;
         }
         ++retryCount;
      }
   }
   catch (Exception ex)
   {
      //SET THE VARIABLES TO BE DISPLAYED ON THE VEND CODE DISPLAY PAGE
      System.Diagnostics.EventLog.WriteEntry("Application", "GENERAL ERROR : " + ex.Message, System.Diagnostics.EventLogEntryType.Information);
      ViewBag.Title = "Vend Code Error";
      ViewBag.Message = "An error has occurred while retrieving your vend code. Please contact our customer service team.";
      return View("Info");
   }
   //SET THE VARIABLES TO BE DISPLAYED ON THE VEND CODE DISPLAY PAGE
   if(isVoucherCreated)
   {
      ViewBag.Title = "Issue Vend Code";
      ViewBag.Message = ViewBag.VendCode;
      return View("Success");
   }
   else
   {
       ViewBag.Title = "Vend Code Error";
       ViewBag.Message = "An error has occurred while retrieving your vend code. Please contact our customer service team.";
       return View("Info");
   }
}