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)

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.


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.

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"/>

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>
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.

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

Need Your Help

ActivityThread Crashing program after deleting something out of an ArrayList

java android arrays collections crash

Ok, So I have this method in my program where I delete an object from an ArrayList. (The method is in the bottom of this post). It does some other stuff aswell, but after debugging alot I found tha...

What's the best way to insert version and arch info into C++ sources?

c++ version autoconf automake

I want my C++ program to include a "--version" option which causes it to print out: