簡體   English   中英

ASP.Net Core MVC RedirectToAction 在 returnUrl 前面附加控制器名稱

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

我正在開發 ASP.Net 核心,MVC 6 應用程序。 我有一個 AppControler 作為我的初始控制器,如果用戶嘗試轉到具有 [Authorize] 屬性的操作,我會重定向到我的 AuthController 進行登錄,並傳入 returnUrl 進行返回。 一旦通過身份驗證,我使用... return RedirectToAction(returnUrl)。

在調試中,我可以看到 returnUrl 字符串設置為 /App/Timesheets。 但是,在瀏覽器地址欄中,它的地址為http://localhost:49940/Auth/%2FApp%2FTimeSheets 出於某種原因,它在 returnUrl 前面附加了控制器名稱 (Auth)。

這是我在 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();
    }

我可以在瀏覽器地址欄中手動輸入http://localhost:49940/App/Timesheets並獲得正確的視圖。 另外,如果我添加

returnUrl = String.Empty;  //Test Only

上線前...

if (string.IsNullOrWhiteSpace(returnUrl))

使其執行該行...

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

重定向工作得很好。 所以它與以"/Controller/Action"格式傳遞字符串變量有關,這就是問題所在。

有什么想法嗎?

當你已經有了一個完整的 URL 時,你應該返回一個Redirect 當前,您正在執行RedirectToAction ,它將嘗試重定向到當前控制器 (Auth) 下的操作。

if (signInResult.Succeeded)
{
   if (string.IsNullOrWhiteSpace(returnUrl))
   {
      return RedirectToAction("Timesheets", "App");
   }
   else
   {
      return Redirect(returnUrl);
   }
}
var redirect = RedirectToAction();
redirect.ActionName = "YourAction"; // or can use nameof("") like  nameof(YourAction);
redirect.ControllerName= "YourCtrl"; // or can use nameof("") like  nameof(YourCtrl);
return redirect;

我想它只是把問題描述寫出來讓我看到問題。

我變了...

return RedirectToAction(returnUrl);

去...

return RedirectToAction(WebUtility.UrlEncode(returnUrl));

現在它工作正常。

:/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM