Reputation: 307
In my MVC5 Application I want to redirect to an action method from a class as following
public static User GetUserObject()
{
if (HttpContext.Current.Session["CurrentUser"] != null)
{
User currentUser = HttpContext.Current.Session["CurrentUser"] as User;
return currentUser;
}
else
{
//I want to redirect to the login action method from here
}
}
Upvotes: 0
Views: 1274
Reputation: 10824
You can do that, But it's not recommended:
else {
var context = new RequestContext(
new HttpContextWrapper(System.Web.HttpContext.Current),
new RouteData());
var urlHelper = new UrlHelper(context);
var url = urlHelper.Action("About", "Home");
System.Web.HttpContext.Current.Response.Redirect(url);
return new User();
}
I think it would be better to do this way:
public static User GetUserObject()
{
return HttpContext.Current.Session["CurrentUser"] as User;
}
Then inside your action method:
public ActionResult Index()
{
var userObject = Helpers.Helper.GetUserObject();
if (userObject == null)
return RedirectToAction("actionName", "controllerName");
else
return RedirectToAction("", "")
//
}
Upvotes: 2