Reputation: 727
I am trying to add forms authentication to an mvc site and when i run the application I am redirected to the login page (which is correct). However, everytime I try to log in, the page is just refreshed instead and the controller is never getting the post request. I think something with my forms authentication is off and its redirecting all requests back to the login page? Any help would be greatly appreciated!
below is my web config info:
<authentication mode="Forms">
<forms loginUrl="~/Account" timeout="30" slidingExpiration="false" requireSSL="false" />
</authentication>
<authorization>
<deny users ="?" />
<allow users = "*" />
</authorization>
Below is my login page:
@using (Html.BeginForm("Login", "Account", FormMethod.Post))
{
@Html.LabelFor(x => x.Username)<br />
@Html.TextBoxFor(x => x.Username)
<br />
<br />
@Html.LabelFor(x => x.Password)<br />
@Html.TextBoxFor(x => x.Password)
<br />
<br />
<br />
<input type="submit" value="Login" />
}
Below is my controller:
[HttpGet]
public ActionResult Index()
{
return View("~/Views/Account/Login.cshtml", new LoginViewModel());
}
[HttpPost]
public ActionResult Login(LoginViewModel viewModel)
{
Membership.ValidateUser(viewModel.Username, viewModel.Password);
FormsAuthentication.SetAuthCookie(viewModel.Username, viewModel.RememberMe);
return View("~/Views/Account/Login.cshtml", viewModel);
}
Upvotes: 2
Views: 5310
Reputation: 124794
Others have suggested redirecting to the home page from your Login HttpPost action, but the standard MVC "Intranet Application" template created by Visual Studio attempts to redirect to the returnUrl that is passed to the Login action as a query string by the FormsAuthentication infrastructure:
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
I would copy this unless you have a good reason not to.
Upvotes: 2
Reputation: 67918
I believe the POST
is occuring, but the issue you have my friend is that you're redirecting to the login page at the end of the POST
.
return View("~/Views/Account/Login.cshtml", viewModel);
Direct the user to the home page.
Upvotes: 2
Reputation: 1955
It's correct. Because of that code:
public ActionResult Index()
{
return View("~/Views/Account/Login.cshtml", new LoginViewModel());
}
Change it to return View();
and create View named Index in the appropriate folder.
Upvotes: 1