2

I am trying to setup a Login form in an ASP.NET MVC 4 app. Currently, I have configured my view as shown here:

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");
}

When I attempt to visit /account/login in the browser, I receive an error that says:

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

How do I setup a basic form in ASP.NET MVC 4? I've looked at the sample Internet App template in ASP.NET MVC 4. However, I can't seem to figure out how the routing is wired up. Thank you so much for your help.

Bill Jones
  • 701
  • 4
  • 16
  • 24

1 Answers1

7

I haven't tried this yet but can you try annotating your Login actions with the appropriate Http Verb - I'm assuming that you're using a GET for viewing the login page and a POST for processing the login.

By adding [HttpGet] for the first action and [HttpPost] for the second action the theory is that ASP.Net's routing will then know which Action method to call based upon which method has been used. Your code should then look something like this:

[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");
}

If this doesn't work, consider having two routes and two differently named actions like below:

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

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

There are other similar questions and answers on StackOverflow already, take a look at: How to route GET and DELETE for the same url and there is also the ASP.Net documentation which might also help.

Community
  • 1
  • 1
Tom Scott
  • 352
  • 1
  • 10