【问题标题】:RedirectToAction won't works, it runs but do not route to the urlRedirectToAction 不起作用,它运行但不路由到 url
【发布时间】:2017-04-06 01:33:18
【问题描述】:

谢谢!!

我有一个问题。

RedirectToAction 不起作用,它运行但不路由到 url

它首先运行编辑控制器

    public ActionResult Edit(int? id)
    {
        CheckAccess();

        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }  

         .....
    }

它将访问 CheckAccess() 方法,当它运行 return RedirectToAction("错误", "索引");它运行正常但没有路由到 url,然后返回“编辑”控制器并运行下一个命令“if (id==null)。

    public ActionResult CheckAccess()
    {
        int StaffUserType = 5;
        if (Session["StaffUserType"] != null)
            StaffUserType = Convert.ToInt32(Session["StaffUserType"]);

        if (StaffUserType == 5)
        {

            //return Json(Url.Action("Index", "Error"));
            return RedirectToAction("Error", "Index");
            //return View("ErrorController/Index");

        }
        else
            return View();
        }
    }

【问题讨论】:

  • return RedirectToAction("Index", "Error", new { id = StaffUserType }); 是正确的用法。动作名称应作为第一个参数提及,然后是控制器名称。
  • 你的if (id == null) 有什么意义 - 你已经退出了,永远不会到达那行代码。

标签: c# asp.net-mvc


【解决方案1】:

Edit() 永远不会返回 RedirectToAction Result,因为 CheckAccess() 的返回值不会被捕获和返回。

您可以修改 CheckAccess() 以返回布尔值

public bool CheckAccess()
{
    int StaffUserType = 5;
    if (Session["StaffUserType"] != null)
        StaffUserType = Convert.ToInt32(Session["StaffUserType"]);

    if (StaffUserType == 5)
    {
        return false;
    }
    else
    {
        return true;
    }
}

然后在 Edit 中检查这个结果,如果结果为 false,则返回 RedirectToAction。

public ActionResult Edit(int? id)
{
    if (!CheckAccess())
    {
        return RedirectToAction("Index", "Error");
    }

    .....
}

【讨论】:

    猜你喜欢
    • 2017-05-31
    • 2020-03-01
    • 2019-11-03
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-11
    • 1970-01-01
    相关资源
    最近更新 更多