Johny Bravo
Johny Bravo

Reputation: 424

MVC Routing and session

I am developing a MVC application with Windows authentication. We have a login module developed for windows auth, so when any user tries to access this application is redirected to the login page for windows auth, hosted elsewhere. After it validates user, it returns user information and here I am creating session for the user. This works fine.

Now consider 2 scenarios 1. if user tries to access http://localhost:63145/Home/Index , he is redirected to login page and it return the control back to Index method of Home Controller where I create session.

  1. if user tries to access http://localhost:63145/Product/Index, , he is redirected to login page and it return the control back to Index method of Product controller where I am not creating any session.

So in case 2, user's sessions are not created. What should be the better approach here?

Upvotes: 0

Views: 1042

Answers (1)

Emre Bolat
Emre Bolat

Reputation: 4562

Create a BaseController like this;

public class BaseController : Controller
    {
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            InitAppController(filterContext);
            base.OnActionExecuting(filterContext);
        }

        // Redirect to login page if user's session is not valid.
        public void InitAppController(ActionExecutingContext filterContext)
        {
            if (/* Check Session Condition Here */)
            {
                filterContext.Result = RedirectToAction("Index", "Login");
            }
        }
    }

Then, change all of your controllers;

HomeController : Controller to HomeController : BaseController

ProductController : Controller to ProductController : BaseController

Upvotes: 1

Related Questions