Home > Net >  The refactoring method must either RedirectToAction or do nothing. How can I achieve that?
The refactoring method must either RedirectToAction or do nothing. How can I achieve that?

Time:03-28

I'm trying to refactor my controller code. I want to extract a piece of code used in any method of my controller, but this piece of code could either return a RedirectToAction or do nothing. I don't see how I can write my refactor method in order to have two different return types.

My explanation seems a bit confuse but the code is really simple:

This is the code I want to refactor

 public async Task<IActionResult> Texts()
 {
    var model = new FeaturesViewModel();
    try
    {
        // The code I want to extract
        var currentPage = await _customersRepository.GetCustomersPageAsync(currentRoute);
        if (currentPage == null)
        {
           return RedirectToAction("Error", "Home", new { statusCode = 404 });
        }
        this.RouteData.SetPage(currentPage);

        // any code
    }
    catch (Exception ex)
    {
        // any code
    }
    return View(model);
}

This is the new code:

 public async Task<IActionResult> Texts()
 {
    var model = new FeaturesViewModel();
    try
    {
        // extracted code 
        await GetCurrentPageAsync(this.RouteData.GetRoute());

        // any code
    }
    catch (Exception ex)
    {
        // any code
    }
    return View(model);
}

// the new method which will be using in every action
private async Task<IActionResult> GetCurrentPageAsync(string currentRoute)
{
   var currentPage = await _customersRepository.GetCustomersPageAsync(currentRoute);
   if (currentPage == null)
   {
       return RedirectToAction("Error", "Home", new { statusCode = 404 });
   }
   this.RouteData.SetPage(currentPage);

   // the problem is : when I get to this line, it doesn't return to the calling method...
}

I haven't tried much because I am wondering whether this is achievable or this is a design dead-end?

I've tried passing the name of the action as parameter and do a "return RedirectToAction(action_parameter)". But of course, this is not working as I return back at the beginning of the action and not from where I left.

CodePudding user response:

I have resolved that issue this way :

private async Task<IActionResult> GetCurrentPageAsync(string currentRoute)
{
    var currentPage = await _customersRepository.GetCustomersPageAsync(currentRoute);
    if (currentPage == null)
     {
         return RedirectToAction("Error", "Home", new { statusCode = 404 });
     }
    this.RouteData.SetPage(currentPage);


    return Ok();
}
  • Related