question

mehmoodtekfirst-9443 avatar image
0 Votes"
mehmoodtekfirst-9443 asked mehmoodtekfirst-9443 commented

Redirection fails

Hi,

I want to write a post filter and want to place at top of my web api method.

This is my web api function. What I want that is to call through JavaScript and once I got the response from this API. After this success call, a post call will redirect to Home controller and FindBranch Action/View. Now if possible then I want to do it by placing an attribute over my checkoutofhours service/api.

 [HttpPost("checkoutofhours")]
         public async Task<ActionResult<Tuple<bool, string, decimal, decimal>>> CheckOutOfHrs([FromBody]  HomeSearch model)
         {
             if (!ModelState.IsValid)
             {
                 _logger.LogError("Invalid owner object sent from client.");
                 return BadRequest("Invalid model object");
             }
    
             try
             {
                 string lStrWarningMsg;
                 decimal lIntOutOfHrsSurcharge;
                 decimal lIntWeekendSurcharge;
                 int franchiseId = model != null && model.FranchiseId.HasValue ? model.FranchiseId.Value:0;
                 List<Franchise_BankHolidays> resultSet = await _repository.IsBankHoliday(franchiseId, model!.StartDate, model.EndDate, model.StartTime, model.EndTime);
    
                 bool isBankHoliday = resultSet.Any();
                 if (isBankHoliday)
                 {
                     lStrWarningMsg = "Sorry, we are having an Off on your selected Date or Time. Please choose another Date or Time";
                     return new Tuple<bool, string, decimal, decimal>(true, lStrWarningMsg.Replace("'", "\\"),0,0);
                 }
    
                 BookingVM? bp = HttpContext.Session.Get<BookingVM>("BookingProcess");
                 if (model.FranchiseId == 0)
                 {
                     model.FranchiseId = bp != null && bp.HomeSearch != null ? bp.HomeSearch.FranchiseId : 0;
                 }
    
                 Tuple<bool, string, decimal, decimal> applyOpeningHrs = await _repository.ApplyOpeningHrsAndWeekendSurchrge(franchiseId, model.StartDate, model.EndDate, model.StartTime, model.EndTime);
                 lIntOutOfHrsSurcharge = applyOpeningHrs.Item3;
                 lIntWeekendSurcharge = applyOpeningHrs.Item4;
                 lStrWarningMsg = applyOpeningHrs.Item2;
                 if (bp == null)
                 {
                     bp = new BookingVM
                     {
                         HomeSearch = model,
                         PaymentDetails = new PaymentDetails { OpeningHrsSurcharge = lIntOutOfHrsSurcharge }
                     };
                 }
                 else if (bp.PaymentDetails == null)
                 {
                     bp.PaymentDetails = new PaymentDetails { OpeningHrsSurcharge = lIntOutOfHrsSurcharge };
                 }
                 else
                 {
                     bp.PaymentDetails.OpeningHrsSurcharge = lIntOutOfHrsSurcharge;
                 }
    
                 if (HttpContext.Session.Get<BookingVM>("BookingProcess") == default)
                 {
                     HttpContext.Session.Set<BookingVM>("BookingProcess", bp);
                 }
    
                 return applyOpeningHrs;
             }
             catch (Exception ex)
             {
                 _logger.LogError(ex.Message);
                 return new Tuple<bool, string, decimal, decimal>(true, "There is something wrong while getting Out Of Hours.", 0, 0);             
             }
         }


and this is the the second call which I need to call after checkoutofhours.

 public class HomeController : Controller
     {
         private readonly ILogger<HomeController> _logger;
    
         public HomeController(ILogger<HomeController> logger)
         {
             _logger = logger;
         }
    
         public IActionResult FindBranch(int franchiseId = 0)
         {
             ViewBag.SrvDtTime = DateTime.Now.ToString("MM/dd/yyyy HH:mm");
             BookingVM? lObjBooking = HttpContext.Session.Get<BookingVM>("BookingProcess");
                
             ViewBag.Booking = lObjBooking;
             HttpContext.Session.Set<BookingVM?>("upgradeCar", null);
             ViewBag.FranchiseId = franchiseId;            
    
             return View();
         }
 }


This was my previous way to deal this issue through JavaScript


 const getCheckOutOfHrs = async(obj) => {                          
             //let abortController = new AbortController();
             let lattitude = 0;
             let longitude = 0;
             let resultPages = [];                                    
             let apiUrl = REACT_APP_CheckOutOfHours;       
             const settings = {
                 method: "POST",               
                 headers: {
                     "Content-Type": "application/json"
                 },
                 body: JSON.stringify(obj)
                 //,signal: abortController.signal
             };      
         const responseDetail = await fetch(apiUrl, settings)/*.then( (dataRes) => { 
                 //debugger;
                 if (dataRes.ok) {                  
                     return dataRes.json();
                 } else {
                     return Promise.reject(dataRes);
                 }
             }).catch(function (err) {
                // debugger;
                 return err;
             });*/
         //abortController.abort();
         if (responseDetail && !responseDetail.ok) {  
                 resultPages = [];                               
          }
          else {
                 resultPages =  await responseDetail.json(); 
          }                    
    
         try {          
             let OutOfHours = responseDetail;;            
             debugger;
             if(OutOfHours)
             {                             
                 if (OutOfHours && OutOfHours.item2 && OutOfHours.item2.indexOf("£") > 0) {                        
                     //window.location = "/Home/FindBranch/?franchiseId=" + obj.FranchiseId;                    
                    let redirectLocalUrl = "/Home/FindBranch/?franchiseId=" + obj.FranchiseId;
                    window.location.replace(redirectLocalUrl);                                    
                    // window.location.href = redirectLocalUrl;
                   //  windowtruelocation.assign(redirectLocalUrl);                    
                     return true;
    
                 } else if (OutOfHours && OutOfHours.item2 && OutOfHours.item2.indexOf("£") < 0) {
                         //OutOfHours = OutOfHours.replace("\\", "'").replace("\\", "");                        
                     alert(OutOfHours.item2);
                         return false;
                     } else {
                            
                     //window.location = "/Home/FindBranch/?franchiseId=" + obj.FranchiseId;                     
                     let redirectLocalUrl = "/Home/FindBranch/?franchiseId=" + obj.FranchiseId;
                     window.location.replace(redirectLocalUrl);                    
                    // window.location.href = redirectLocalUrl;
                    // window.location.assign(redirectLocalUrl);
                     return true;                    
                     }
                 } 
              
         } catch (error) {
             debugger;                               
       }  
 };

  $('#btn-search-car').click(function (e) { e.preventDefault(); searchCar(e) });
    
 function searchCar(e) {
  e.preventDefault();
 var obj = {Branch: lStrLocNam.trim(), PickupLocId: lIntPickupLocId,
                  FranchiseId: lIntFranchiseId, SubofficeId: lIntSubofficeId,
                  StartDate: dtStart/*startDate*/, StartTime: startTime,
                  EndDate: dtEnd/*endDate*/, EndTime: endTime,
                  VehicleType: selectedVehType, VehicleCategoryId: carCat, IsNewSearch: true
                  };
    
 getCheckOutOfHrs(obj);
 }


This solution work sometimes and sometimes don't. can anyone tell me what is the issue with it or can guide by creating a post filter .


I have tried with promises please check my function here.

Again this work sometimes and sometimes not. please try it and if you find any improvement then please share. thanks

   const getCheckOutOfHrs = (obj) => {                 
             let resultPages = [];
             let apiUrl = REACT_APP_CheckOutOfHours;
             const settings = {
                 method: "POST",
                 headers: {
                     "Content-Type": "application/json"
                 },
                 body: JSON.stringify(obj)               
             };
             const responseDetail = fetch(apiUrl, settings).then(response => response.json())
                 .then((dataRes) => { 
                     debugger;
                     if (dataRes) {                  
                         let OutOfHours = dataRes;
                         debugger;
                         if (OutOfHours) {                               
                             if (OutOfHours && OutOfHours.item2 && OutOfHours.item2.indexOf("£") > 0) {                               
                                 let redirectLocalUrl = "/Home/FindBranch/?franchiseId=" + obj.FranchiseId;                            
                                 window.location.replace(redirectLocalUrl);                                                                                   
                                 return true;
                             } else if (OutOfHours && OutOfHours.item2 && OutOfHours.item2.indexOf("£") < 0) {                              
                                 alert(OutOfHours.item2);
                                 return false;
                             } else {
                                 let redirectLocalUrl = "/Home/FindBranch/?franchiseId=" + obj.FranchiseId;                            
                                 window.location.replace(redirectLocalUrl);                    
                                 return true;
                             }
                         }
                     } 
                 }).catch(function (err) {                 
                     return err;
                 });
         };



dotnet-aspnet-core-mvcdotnet-aspnet-core-webapi
· 8
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

The redirection fails because fetch is an asynchronous call but you are treating it as synchronous. Basically you crafted a race condition. Write code within the then() promise to control the code flow.



1 Vote 1 ·

It seems like that but I have tried by using then as well

0 Votes 0 ·
AgaveJoe avatar image AgaveJoe mehmoodtekfirst-9443 ·

It seems like that but I have tried by using then as well

Again, your current code has a race condition due to not handling asynchronous code correctly. Your commented code that uses the then() promise does not redirect the browser. Please debug your logic using the standard tooling; Visual Studio and the browser's dev tools.




1 Vote 1 ·
Show more comments

0 Answers