在我的MVC5应用程序中,我想从类中重定向到一个动作方法,如下所示
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
}
}
答案 0 :(得分:1)
你可以这样做,但不推荐:
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();
}
我认为这样做会更好:
public static User GetUserObject()
{
return HttpContext.Current.Session["CurrentUser"] as User;
}
然后在你的行动方法中:
public ActionResult Index()
{
var userObject = Helpers.Helper.GetUserObject();
if (userObject == null)
return RedirectToAction("actionName", "controllerName");
else
return RedirectToAction("", "")
//
}