I'm trying to create a login form for my MVC 5 project. I've already got authentication working, so my controller is decorated with [Authorize]. When I launch my project, I am rightly directed to my anonymous Login action:
[HttpGet]
[AllowAnonymous]
public ActionResult Login()
{
return View();
}
I have setup my POST form in this view. The generated HTML looks fine.
I then add a new method that should accept the form submission:
[HttpPost]
[AllowAnonymous]
public ActionResult Login(FormCollection formCollection)
{
...
I have found that when I submit a form, my first Login method is called -- apparently a redirect caused by some authentication issues. (A Fiddler trace shows that my form, while POST, gets sent to /Login?key=myKeyHere instead of being POSTed to /Login with key=myKeyHere as a form entry. Further, if I change my authentication's redirect URL from /Login to /SomethingElse, a form submission gets me redirected to /SomethingElse instead of posting it to /Login.)
If I remove [Authorize] from my controller, my form submission goes through just fine.
It doesn't appear to be an issue with my two methods being the same name (Login), as I can rename the method that accepts a POST, change my form's action, and submit to that, and I am redirected to my GET login page again.
What do I have to do to post a form to an [AllowAnonymous] method?
Update to include my View My view already uses a POST action:
@using (Html.BeginForm("Login", "Home", FormMethod.Post))
{
@Html.TextBox("key", string.Empty, new { @class = "input_centered", id = "key_text"})
<input type="submit" id="key_submit" class="enter" name="submit" value="Enter" />
}
The generated HTML looks good:
<form action="/Login" method="post">
<input class="input_centered" id="key_text" name="key" type="text" value="" />
<input type="submit" id="key_enter" class="enter" name="submit" value="Enter" />
The issue is you are using FormCollection object, it is too broad and MVC engine can not construct or map (de-serialise) your posted data to FormCollection object therefore can't find any matching Action for post. Try to convert your FormCollection into a serializable object.
eg.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel model)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With