D'Arcy Rittich
D'Arcy Rittich

Reputation: 171351

How do I find out the name of the current controller/action/view?

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.

Upvotes: 0

Views: 523

Answers (3)

D'Arcy Rittich
D'Arcy Rittich

Reputation: 171351

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

Upvotes: 1

user1151
user1151

Reputation:

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.

Upvotes: 4

MrJavaGuy
MrJavaGuy

Reputation: 676

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.

Upvotes: 2

Related Questions