当我重定向到另一个控制器的Action时,我的会话变为null,我该怎么办?
答案 0 :(得分:1)
关于你发给我的评论,这是我的想法。在您需要会话的Controller中使用类似于此的内容:
//Controller A
public class TheController : Controller
{
public ActionResult Index(){
Session["yourSession"] = "Hello World";
return View();
}
}
//Controller B
public class MyController : Controller
{
string textString;
protected override void OnActionExecuting(ActionExecutingContext ctx)
{
base.OnActionExecuting(ctx);
textString = ctx.HttpContext.Session["yourSession"].ToString();
}
public ActionResult Index(){
string currentText = textString;
return View();
}
}
我测试了(http://stackoverflow.com/questions/889516/session-null-in-asp-net-mvc-controller-constructors)的建议,会议内容可用。
答案 1 :(得分:1)
我意识到我在登录时设置新会话之前正在清理并销毁所有会话
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
Session.Abandon();
Session.Clear();
当我删除这些行时,所有内容都像@Clayton一样开始工作,所以我删除了这些行并将其替换为Session.Remove('sessionvariablename')
,我仍然不确定上述行导致的问题,但我的代码开始工作
答案 2 :(得分:1)
您必须使用会话属性创建一个唯一的基本控制器,然后项目中的所有控制器都将从该BaseController继承:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MonitoringCSP.Controllers
{
//[AllowAnonymous]
//[Authorize(Roles = "admin")]
public class BaseController : Controller
{
private HttpSessionStateBase _session;
protected HttpSessionStateBase CrossControllerSession
{
get
{
if (_session == null) _session = Session;
return _session;
}
set {
_session = Session;
}
}
}
}
使用示例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using MonitoringCSP.Models;
namespace MonitoringCSP.Controllers
{
[AllowAnonymous]
public class AccountController : BaseController
{
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
/*session*/
CrossControllerSession["UserName"] = User.Identity.Name;
/*end session*/
return RedirectToAction("someAction");
}
}
}