Search code examples
c#model-view-controller

How to RedirectToAction using string


I am new to MVC so would appreciate any help on the following.

I have an AuthController for Login and if there is a returnUrl I would like to return to that url. It seems to be looking in the current controller (Auth) for the returnUrl (/App/Trips) but if I specify the controller it works fine.

Any ideas on why RedirectToAction(returnUrl) does not work but RedirectToAction("Trips", "App") does?

I wonder if it has any thing to do with mapping? This is what I have:

Mapping in Startup.cs

config.MapRoute(
    name: "Default",
    template: "{controller}/{action}/{id?}",
    defaults: new { controller = "App", action = "Index" }
);  

AuthController.cs

[HttpPost]
public async Task<ActionResult> Login(LoginViewModel vm, string returnUrl)
{
    if(ModelState.IsValid)
    {
        var signInResult = await _signInManager.PasswordSignInAsync(vm.Username, vm.Password, true, false);

        if (signInResult.Succeeded)
        {
            if(string.IsNullOrWhiteSpace(returnUrl))
            {
                return RedirectToAction("Trips", "App");
            }
            else
            {
                //return RedirectToAction(returnUrl);       // Doesn't work - tries to find /App/trips under /Auth 
                return RedirectToAction("Trips", "App");    // Works! goes straight to /App/trips

            }
        }
        else
        {
            ModelState.AddModelError("", "Username or Password is incorrect");
        }
    }

    return View();
}

returnUrl value when above run = "/App/trips"

PASS when

return RedirectToAction("Trips", "App");

Goes to http://localhost:12345/App/Trips as expected

FAIL when

return RedirectToAction(returnUrl);

Page not found error http://localhost:12345/Auth/%2FApp%2Ftrips


Solution

  • In RedirectToAction we need to pass Controller Name and Action Name as parameter while Redirect() only requires Url

    All you need is to do following

       return Redirect(returnUrl);