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.

Need Your Help

SQL query for sorting leaderboard

mysql sql sql-server sql-server-2008 tsql

What is the most efficient SQL query for leaderboards if we have table:

Saving data into DB s considered Serialization?

c# serialization

Serialization -> Convert an object to a binary representation that can be then written to Disk or write on a file..