Reputation: 4662
I just created my first C# Razor MVC3 project. I've dabbled in it before but this is the first time I created one.
Anyhow, I have a simple question. I am using the MembershipProvider
AspNetSqlProfileProvider
that was build with the default project.
My question is simple, where and how do I check if the user is logged on before it loads the Home/Index.cshtml
so that I can direct them to another page?
If they are logged on, I want to take them to the customer portal.
If they are not logged on, I want to take them to the logon screen.
Upvotes: 1
Views: 8983
Reputation: 25551
A more generic way to set this up would involve 2 steps:
First, add an [Authorize] attribute to your action that you are securing:
[Authorize]
public ActionResult Index() {
}
This will make sure that the user has authenticated (using FormsAuthentication).
Second, in your Web.config file, set the URL that you want the user to be redirected to when they need to login.
<authentication mode="Forms">
<forms name="cookieName" loginUrl="~/Account/LogOn" timeout="30" domain=".example.com" slidingExpiration="true" />
</authentication>
Upvotes: 2
Reputation: 13226
The page (url rather) which the user is redirected to if not logged in is defined in the Web.config
under:
<authentication mode="Forms">
<forms loginUrl="~/Home/GetIn" .... />
</authentication>
If logged in however the ASP.NET MVC routing kicks in, which is in Global.asax.cs
and by default has this route:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new {
controller = "Home",
action = "Index",
id = UrlParameter.Optional
} // Parameter defaults
Which means that if no controller or action were specified in the URL then it will default to Home
and Index
Upvotes: 0
Reputation: 8818
Couple of options here. You could do it in your home/index view (if that's what you're calling it), and then just use something like:
if(Request.IsAuthenticated())
return RedirectToAction("login","login");
Or you could probably do it in the application startup method. I'd probably just do the first one, though.
Upvotes: 2