Reputation: 23
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
Upvotes: 1
Views: 763
Reputation: 21
If you're encountering issues with converting the forward slash '/' to an encoded string when using RedirectToAction
, you can try using the Url.Action method instead. Here's how you can modify your code:
return Redirect(Url.Action("Show", new { id = id }));
This will generate the URL correctly without encoding the forward slash.
Show is the Controller function name and id I am passing as the parameter.
Hope, it helps in your code.
Upvotes: 0
Reputation: 1067
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);
Upvotes: 2