Reputation: 2036
Title says it all, i want it so if the user tries to navigate to any page or access anything in the website to be redirected to a login page, that's only if hes not logged in.
This is my simple login code :
public ActionResult login(MvcMobile.Models.Users x)
{
var user = db.Users.FirstOrDefault(u => u.username == x.username && u.password == x.password);
if (user == null)
ModelState.AddModelError("","username or password is wrong.");
else
{
FormsAuthentication.SetAuthCookie(user.username, false);
Response.Redirect("/");
}
return View(user);
}
i tried to place this code in the main layout, but i got an infinite redirect loop :P
@if (User.Identity.IsAuthenticated)
{
<p> Hi @User.Identity.Name</p>
}
else
{
Response.Redirect("~/home/login");
}
any idea ?
Upvotes: 1
Views: 2719
Reputation: 13003
In addition to Darin Dimitrov's answer, you should also config the LoginUrl attribute at the Web.config file, for example:
<authentication mode="Forms">
<forms loginUrl="member_login.aspx"
defaultUrl="index.aspx" />
</authentication>
Upvotes: 1
Reputation: 1038710
Decorate your controllers/actions with the [Authorize]
attribute instead. Or if you want this to apply to all controllers add it as a global action filter:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new AuthorizeAttribute());
}
Of course by doing this you might want to exclude your AccountController from authentication by decorating it with the [AllowAnonymous]
attribute:
Then in your web.config, set the loginUrl
page of your forms authentication tag to point to the login page where all anonymous users will be redirected to:
<authentication mode="Forms">
<forms loginUrl="~/home/login" />
</authentication>
Upvotes: 7