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

I have some code that I put in the code behind the main page. This master page is my main layout and the purpose of the code is to check if the user is logged in and take appropriate action depending on whether they are or not. I would be interested to hear alternative methods on how to approach this, but I am doing it this way at the moment as it is a direct port from another MVC framework and I want to change as little code or thread as possible during port.

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

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

      

So, I need to know if I'm on the login page to avoid the endless redirect loop. I am currently achieving this by looking into the Url to see if it contains the string / Login /, but this is hacky and I would rather use a more reliable and intelligent method.

0


source to share


3 answers


Take a look at the authorization attribute for controller and controller actions. This should save you the trouble of doing anything in the code behind the main page.



+2


source


The best check to see if a user is logged in (assuming you are using FormsAuth) is User.Identity.IsAuthenticated, accessible from Views or Controller.

It looks to me like you need to hook 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 application that you are using auth forms. Then use an ActionFilter for the methods you want to block:

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

      

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

+4


source


Please note that there are several ways to transfer data to the main pages identified here .

+1


source







All Articles