在ASP.NET MVC 4中路由GET和POST路由

Bil*_*nes 2 asp.net-mvc-4

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

RouteConfig.cs

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

MyController.cs

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

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

当我尝试在浏览器中访问/ 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
Run Code Online (Sandbox Code Playgroud)

如何在ASP.NET MVC 4中设置基本表单?我已经看过ASP.NET MVC 4中的示例Internet App模板.但是,我似乎无法弄清楚路由是如何连接的.非常感谢你的帮助.

小智 7

我还没试过这个,但是你可以尝试用适当的Http Verb注释你的登录操作 - 我假设你正在使用a GET来查看登录页面和a POST来处理登录.

通过添加[HttpGet]第一个动作和[HttpPost]第二个动作,理论是ASP.Net的路由将根据使用的方法知道要调用哪个Action方法.您的代码应该如下所示:

[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");
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

StackOverflow上还有其他类似的问题和答案,请看一下:如何为同一个URL路由GET和DELETE,还有ASP.Net文档也可能有所帮助.