ViVi
ViVi

Reputation: 4464

Redirecting user to another view if not logged in

I am working on a user management functionality right now. I am trying to add authorization and redirect user to my login page if he is trying to access the user management page like this before logging in:

[HttpGet]
public ActionResult UsersList()
{
    if (Session["UserName"] == null)
    {
        RedirectToAction("Login", "Login");
    }
    else
    {
        var User = new User();
        User.usersList = DBManager.Instance.GetUsersList();
        User.PreferedLanguages.Add(new SelectListItem { Text = "ENGLISH", Selected = true, Value = "ENGLISH" });
        User.PreferedLanguages.Add(new SelectListItem { Text = "DUTCH", Value = "DUTCH" });
        return View(User);
    }
}

But I should return a view for an action result right? This code doesn't compile and I get the following error :

Error 4 'WebApplication9.Controllers.UserManagementController.UsersList()': not all code paths return a value >E:\Work\WebApplication9\Controllers\UserManagementController.cs

At this point is it possible to return another controllers view?

Upvotes: 1

Views: 2600

Answers (1)

Mikhail Tulubaev
Mikhail Tulubaev

Reputation: 4251

You should use the following code:

return RedirectToAction("Login", "Login");

instead of simple RedirectToAction.

ActionResult is set of instructions, which will be performed by a action invoker after action will be completed. RedirectToActionResult (the return type of RedirectToAction) contains instructions which should be written to Response for performing correct redirect.

As far as I understood, this is how action invoking works, maybe official documentation has another opinion about this.

Upvotes: 1

Related Questions