2013-01-24 96 views
2

我想在ASP.NET MVC 4应用程序中设置登录表单。目前,我已经配置了我的看法如下所示:在ASP.NET MVC中路由GET和POST路由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"); 
} 

当我试图访问在/帐号/登录浏览器,我收到一个错误,说:

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应用程序模板。但是,我似乎无法弄清楚路由是如何连接的。非常感谢你的帮助。

+0

你想用自定义路线实现什么?乳清没有保留默认路线({controller}/{action}/{id})?默认路线应该可以正常工作。 –

+0

@KevinJunghans - 如果您没有注意到,他的控制器名称与他的网址不同 –

+1

什么是[[ViewSettings(Minify = true)]?我无法找到对此属性的任何参考。这是你创造的东西吗? –

回答

7

我还没有尝试过这一点,但你可以尝试使用适当的Http Verb注释你的登录操作 - 我假设你使用GET来查看登录页面和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"); 
} 

如果这不起作用,考虑有两个路线,两种不同命名的动作象下面这样:

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这也可能有所帮助。

+0

第一种是普遍接受的方式来处理它,虽然'[HttpGet]'是可选的,在大多数情况下不需要。 –

+0

你也希望两种方法都有'[AllowAnonymous]'。 –