【问题标题】:Problem with RedirectoAction in Layout for logging out用于注销的布局中的 RedirecttoAction 问题
【发布时间】:2020-11-03 07:13:13
【问题描述】:

我在这样的共享布局中有一个 ActionLink

@Html.ActionLink("Logout", "Logout", "Home", new { @class = "navbar-btn btn btn-login" })

在 Home 的控制器中

public ActionResult Logout()
    {
        Session.Abandon();
        Response.Cookies.Clear();

        return RedirectToAction("Login","Home");
    }

然后当我按下Logout按钮时,如果网页在/Home内,它会正确返回/Home/Login,所有会话都被清除。但是当我尝试在/Home 之外按注销时会出现问题,例如在/CourseUser,则返回的URL是/CourseUser/Logout?Length=4并且它不存在

我想要的是在我按下“注销”时在任何情况下都返回 URL '/Home/Logout'

【问题讨论】:

    标签: asp.net-mvc razor actionresult redirecttoaction


    【解决方案1】:

    @Html.ActionLink 将生成一个链接。单击它将导致向服务器发出 HttpGet 请求。这对于任何不改变任何状态的东西都很好,因为 HttpGet 操作应该是幂等的——多次调用它具有相同的效果。

    对于注销,我认为最佳实践和标准建议使用 HttpPost,您可以使用隐藏的表单发布来实现:

    <a href="javascript:$('#form-logout').submit();">
        Logout
    </a>
    
    @using(Html.BeginForm("logout", "account", new { area = "" }, FormMethod.Post, 
      new { @id = "form-logout", @class = "d-none" }))
    {
        @Html.AntiforgeryToken();
    }
    

    点击链接会触发隐藏表单的提交,会回传控制器中定义的注销方法,命名为AccountController,例如:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Logout()
    {
        Session.Abandon();
        Response.Cookies.Clear();
    
        return RedirectToAction("index", "dashboard", new { area = "" });
    }
    

    【讨论】:

      【解决方案2】:

      只需在第四个参数中添加 null 如下:

      //parameters in order: title, action name , controller name , route values, html attributes
      @Html.ActionLink("Logout", "Logout", "Home",null, new { @class = "navbar-btn btn btn-login" })
      

      或者你可以在不添加html属性的情况下这样做

      //parameters in order: title, action name , controller name
      @Html.ActionLink("Logout", "Logout", "Home" })
      

      【讨论】:

        【解决方案3】:

        https://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/ajax-actionlink-and-html-actionlink-in-mvc/致敬

        问题出在

        @Html.ActionLink("Logout", "Logout", "Home", new { @class = "navbar-btn btn btn-login" })
        

        本例中的Home路由值,而不是控制器名称。 解决方案:

        @Html.ActionLink("Đăng xuất", "Logout", "Home", null, new { @class = "navbar-btn btn btn-login", @type = "button" })
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-05-20
          • 2018-11-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-05-25
          相关资源
          最近更新 更多