【问题标题】:Routing GET and POST routes in ASP.NET MVC 4在 ASP.NET MVC 4 中路由 GET 和 POST 路由
【发布时间】:2013-01-24 17:30:33
【问题描述】:

我正在尝试在 ASP.NET MVC 4 应用程序中设置登录表单。目前,我已经配置了我的视图,如下所示:

RouteConfig.cs

routes.MapRoute(
  "DesktopLogin",
  "{controller}/account/login",
  new { controller = "My", action = "Login" }
);

MyController.cs

public ActionResult Login()
{
  return View("~/Views/Account/Login.cshtml");
}

[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model)
{
  return View("~/Views/Account/Login.cshtml");
}

当我尝试在浏览器中访问 /account/login 时,我收到一条错误消息:

The current request for action 'Login' on controller type 'MyController' is ambiguous between the following action methods:
System.Web.Mvc.ActionResult Login() on type MyApp.Web.Controllers.MyController
System.Web.Mvc.ActionResult Login(MyApp.Web.Models.LoginModel) on type MyApp.Web.Controllers.MyController

如何在 ASP.NET MVC 4 中设置基本表单?我查看了 ASP.NET MVC 4 中的示例 Internet 应用程序模板。但是,我似乎无法弄清楚路由是如何连接的。非常感谢您的帮助。

【问题讨论】:

  • 您想通过自定义路线实现什么目标?你没有保留默认路由({controller}/{action}/{id})吗?默认路由应该可以正常工作。
  • @KevinJunghans - 如果你没有注意到,他的控制器名称与他的 url 不同
  • [ViewSettings(Minify = true)] 是干什么用的?我找不到对此属性的任何引用。是你创造的吗?

标签: asp.net-mvc-4


【解决方案1】:

我还没有尝试过,但是您可以尝试使用适当的 Http 动词来注释您的登录操作吗?我假设您使用 GET 来查看登录页面并使用 POST 来处理登录。

通过为第一个操作添加[HttpGet],为第二个操作添加[HttpPost],理论上ASP.Net 的路由将根据已使​​用的方法知道要调用哪个操作方法。您的代码应如下所示:

[HttpGet] // for viewing the login page
[ViewSettings(Minify = true)]
public ActionResult Login()
{
  return View("~/Views/Account/Login.cshtml");
}

[HttpPost] // For processing the login
[ViewSettings(Minify = true)]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model)
{
  return View("~/Views/Account/Login.cshtml");
}

如果这不起作用,请考虑使用两条路线和两个不同命名的操作,如下所示:

routes.MapRoute(
   "DesktopLogin",
   "{controller}/account/login",
   new { controller = "My", action = "Login" }
); 

routes.MapRoute(
   "DesktopLogin",
   "{controller}/account/login/do",
   new { controller = "My", action = "ProcessLogin" }
);

在 StackOverflow 上已经有其他类似的问题和答案了,看看:How to route GET and DELETE for the same url 还有ASP.Net documentation 可能也有帮助。

【讨论】:

  • 第一种是公认的处理方式,尽管[HttpGet] 是可选的,在大多数情况下不需要。
  • 这两种方法都需要[AllowAnonymous]
猜你喜欢
  • 2017-03-25
  • 2014-05-25
  • 2013-11-08
  • 2015-07-18
  • 1970-01-01
  • 1970-01-01
  • 2012-09-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多