views:

298

answers:

3

I have some code that I am putting in the code-behind of a master page. This master page is my main layout and the purpose of the code is to check whether the user is logged in and take the appropriate action depending on whether they are or not. I would be interested in hearing alternate methods on how to approach this, but I am doing it this way for now as it is a direct port from another MVC framework, and I want to alter as little code or flow as possible during the port.

My real question is, how do I determine the name of the current controller, action, and view that are being executed? Some of the logic in the code-behind depends on knowing the current page name. To be specific, it says (pseudocode):

if (!isLoggedIn && !isLoginPage)
    Redirect(loginPage);

So, I need to know whether I am on the login page already to avoid an infinite redirect loop. I am currently achieving this by examining the Url to see if it contains the string /Login/, but this is hacky and I would rather use a more robust and intelligent method.

+1  A: 

Take a look at the Authorization attribute for controllers and controllers actions. It should save you from doing anything in the code behind of the master page.

MrJavaGuy
Thanks, I will look into that, but my primary question is how to know what controller/action/view are currently being executed?
RedFilter
If you are in the controller code path, this.RouteData.Values will give you the controller name, the action name and other parameters. Once you are in the view however the controller has been disposed, so there is no way to know.
MrJavaGuy
You can also override the OnResultExecuted method on the controller get all three.
MrJavaGuy
+3  A: 

The best check for whether a user is logged in (assuming you're using FormsAuth) is User.Identity.IsAuthenticated which is reachable from Views or Controller.

Sounds to me like you need to plug in Forms auth here - it handles everything for you, including redirects. In your web.config, make sure this is added:

<authentication mode="Forms">
    <forms loginUrl="~/Account/Login"/>
</authentication>

This tells your app you're using forms auth. Next, use an ActionFilter on the methods you wish to lock down:

/// <summary>
/// Default view
/// </summary>
/// <returns></returns>
[Authorize(Roles="Administrator")]
public ActionResult Index()
{
    return View();
}

This will work with forms auth to make sure the user's identified. It will also append, automatically, the current URL as a Redirect and will ignore the login view - all of it's automatic and done for you.

Rob Conery
A: 

Note there are a number of ways of passing data to master pages outlined here.

RedFilter