Redirection fails

mehmood tekfirst 766 Reputation points
2022-06-14T07:45:00.29+00:00

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;  
                });  
        };  
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,139 questions
{count} votes