ASP.Net Core MVC RedirectToAction is appending controller name in front of returnUrl

别等时光非礼了梦想. 提交于 2019-12-11 05:49:27

问题


I am working on a ASP.Net core, MVC 6 application. I have an AppControler as my initial controller and if a user tries to go to an action that has an [Authorize] attribute, I redirect to my AuthController for the login, passing in the returnUrl for the return. Once authenticated, I use ... return RedirectToAction(returnUrl).

In debug, I can see that the returnUrl string is set to /App/Timesheets. However, in the browser address bar, it has an address of http://localhost:49940/Auth/%2FApp%2FTimeSheets. For some reason it is appending the controller name (Auth) in front of the returnUrl.

Here is my Login action in the AuthController

    [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("Timesheets", "App");
                }
                else
                {
                    return RedirectToAction(returnUrl);
                }
            }
            else
            {
                ModelState.AddModelError("", "Username or password incorrect");
            }
        }

        return View();
    }

I can manually enter http://localhost:49940/App/Timesheets in the browser address bar and get to the correct view. Also, if I add

returnUrl = String.Empty;  //Test Only

before the line...

if (string.IsNullOrWhiteSpace(returnUrl))

to cause it to execute the line...

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

The redirection works just fine. So it has something to do with passing in a string variable in the "/Controller/Action" format that is the problem.

Any ideas?


回答1:


When you have a full URL already, you should return a Redirect. Currently you are doing a RedirectToAction which will try to redirect to an action under the current controller (Auth).

if (signInResult.Succeeded)
{
   if (string.IsNullOrWhiteSpace(returnUrl))
   {
      return RedirectToAction("Timesheets", "App");
   }
   else
   {
      return Redirect(returnUrl);
   }
}



回答2:


I guess it just took writing out the problem description for me to see the problem.

I changed...

return RedirectToAction(returnUrl);

to...

return RedirectToAction(WebUtility.UrlEncode(returnUrl));

and now it is working properly.

:/



来源:https://stackoverflow.com/questions/39280717/asp-net-core-mvc-redirecttoaction-is-appending-controller-name-in-front-of-retur

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!