将应用程序移动到MVC,我认为属性[action]将是处理会话的好地方。
当我逐步完成会话时,会话被设置但在控制器中它是null并且在页面刷新时它不会保持。
提前感谢您的帮助。
属性
public class SetPageDefaultAttribute : ActionFilterAttribute
{
private string _sessionName = "PLANIT";
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
Page page;
page = (Page)HttpContext.Current.Session[_sessionName] as Page;
if (HttpContext.Current.Session[_sessionName] != null)
{
page = (Page)HttpContext.Current.Session[_sessionName] as Page;
}
else
{
// set default page
page = new Page();
}
page.Variables.CurrentController = filterContext.RouteData.Values["controller"].ToString().ToLower();
page.Variables.CurrentAction = filterContext.RouteData.Values["action"].ToString().ToLower();
// return to session
HttpContext.Current.Session[_sessionName] = page;
base.OnActionExecuting(filterContext);
}
}
控制器
[SetPageDefault]
public class LoginController : Controller
{
public ActionResult Login()
{
var f = this.HttpContext.Session["PLANIT"];
return View();
}
}
所以我将属性更改为此...
public class SetPageDefaultAttribute : ActionFilterAttribute
{
private string _sessionName = "PLANIT";
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
Page page;
page = (Page)filterContext.HttpContext.Session[_sessionName] as Page;
if (page != null)
{
}
else
{
// set default page
page = new Page();
}
page.Variables.CurrentController = filterContext.RouteData.Values["controller"].ToString().ToLower();
page.Variables.CurrentAction = filterContext.RouteData.Values["action"].ToString().ToLower();
// return to session
filterContext.HttpContext.Session[_sessionName] = page;
base.OnActionExecuting(filterContext);
}
}
控制器这样做......
[SetPageDefault]
public class LoginController : Controller
{
public ActionResult Login()
{
var f = this.ControllerContext.HttpContext.Session["PLANIT"];
return View();
}
}
页面刷新时它仍为空,因为它再次点击属性
答案 0 :(得分:1)
我不确定这是否有效,但可能是因为您需要在filterContext
内设置OnActionExecuting
范围内的值:
public class SetPageDefaultAttribute : ActionFilterAttribute
{
private string _sessionName = "PLANIT";
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
Page page;
page = (Page)filterContext.HttpContext.Session[_sessionName] as Page;
if (filterContext.HttpContext.Session[_sessionName] != null)
{
page = (Page)filterContext.HttpContext.Session[_sessionName] as Page;
}
else
{
// set default page
page = new Page();
}
page.Variables.CurrentController = filterContext.RouteData.Values["controller"].ToString().ToLower();
page.Variables.CurrentAction = filterContext.RouteData.Values["action"].ToString().ToLower();
// return to session
filterContext.HttpContext.Session[_sessionName] = page;
base.OnActionExecuting(filterContext);
}
}