redirect to action method from base controller
Solution 1
You're calling RedirectToLogin()
which in turn simply returns a RedirectToActionResult
that is not being used and does not affect the flow of the action.
Try this instead:
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting();
if (SessionFactory.CurrentAdminUser == null)
filterContext.Result = new RedirectResult(Url.Action("AdminLogin", "Admin"));
}
Alternatively, if you insist on overriding Initialize
:
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
if (SessionFactory.CurrentAdminUser == null)
{
requestContext.HttpContext.Response.Clear();
requestContext.HttpContext.Response.Redirect(Url.Action("AdminLogin", "Admin"));
requestContext.HttpContext.Response.End();
}
}
Also, check the [Authorize]
filter, it may better suit your needs. See here.
Solution 2
A simpler approach:
public void RedirectToLogin()
{
RedirectToAction("AdminLogin", "Admin").ExecuteResult(this.ControllerContext);
}
DharaPPatel
Updated on February 04, 2022Comments
-
DharaPPatel about 2 years
I have initialized method in my base controller class which is called whenever any action method is executed. On every action method, I want to check my session and if it is null it should redirect to the login page.
public class BaseController : Controller { protected IDataRepository _appData = new DataRepository(); protected override void Initialize(RequestContext requestContext) { base.Initialize(requestContext); if (SessionFactory.CurrentAdminUser == null) { RedirectToLogin(); } } } public ActionResult RedirectToLogin() { return RedirectToAction("AdminLogin", "Admin"); }
it's calling this method but not redirecting to admin login method and keeps execution on and call method which is in flow so error will come.
In short i want to check whenever my application session gets null its should rediect to login page and its not convenient to check on all methods.please suggest me some good way.
-
Silvia almost 8 yearsThank you for your advice, but I couldn't use Url.Action. Can you advice which assembly I need to refer for that Url.Action ?
-
haim770 almost 8 years@Silvia, I assume it's
System.Web.Mvc