我正在尝试在 ASP.NET MVC 4 应用程序中设置登录表单。目前,我已经配置了我的 View ,如下所示:
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 应用程序模板。但是,我似乎无法弄清楚路由是如何连接的。非常感谢您的帮助。
最佳答案
我还没有尝试过,但是你能尝试用适当的 Http 动词来注释你的登录操作吗?我假设你正在使用 GET
查看登录页面和 POST
用于处理登录。
通过为第一个 Action 添加 [HttpGet]
和为第二个 Action 添加 [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");
}
如果这不起作用,请考虑使用两条路线和两个不同名称的操作,如下所示:
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这也可能有帮助。
关于asp.net-mvc-4 - 在 ASP.NET MVC 4 中路由 GET 和 POST 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14507232/