2013-01-24 125 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]'。 –