c# - 重定向网址不正确

标签 c# asp.net asp.net-mvc asp.net-mvc-4

我正在开发一个带有用户登录页面的 MVC 4 项目。一切正常。

问题是当我点击链接注销时,重定向 URL 不正确。

下面是更好解释的代码:

查看:

<a href="@Url.Action("LogOff", "Account")">Logout ?</a>

Controller :

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
  {
     WebSecurity.Logout();

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

当我点击注销链接时,URL 会显示这个 ==> Account/LogOff

但我想重定向到此==> 帐户/登录

有人知道这是怎么回事吗?

最佳答案

在 HTML 中, anchor 元素 ( <a> ) 发送 GET 请求,而不是 POST,因此您的 [HttpPost] Controller 操作永远不会被调用。如果您想调用此操作,您应该使用带有 POST 方法的 HTML 表单:

@using (Html.BeginForm("LogOff", "Account", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    <button type="submit">Logout ?</button>
}

另请注意,我在表单中包含了 AntiForgery token ,因为您的 Controller 操作是用 [ValidateAntiForgeryToken] 装饰的。属性,因此期待它。

关于c# - 重定向网址不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18385789/

相关文章:

c# - 静态与非静态类成员

C#,将一个 bool 复制到另一个(通过 ref,而不是 val)

c# - 迭代 IEnumerable<T> 和 List<T> 之间的性能

javascript - 遍历 ViewData 数组并使用 javascript 代码

c# - 在任务中取消异步任务

c# - System.IO.FileLoadException : Could not load file or assembly 'System. 数据.SQLite

asp.net - 禁用某些控件(但不是全部)的 ASP.NET View 状态

javascript - Javascript 中的撇号和双引号问题

c# - 服务器和客户端验证差异增加了额外的跨度

c# - 如何以编程方式重启 MVC4 项目