0
我发现会话模式为“SQLServer”时发生问题。 我已经分离出下面的例子中的问题:SessionState在会话模式更改时呈现不同的行为
在使用.net 3.5 web应用我有以下各项:
1)两个类:
[Serializable]
public class Foo
{
private List<Bar> bars;
public Foo(List<Bar> bars)
{
this.bars = bars;
}
public List<Bar> Bars
{
get { return bars ?? (bars = new List<Bar>()); }
}
}
[Serializable]
public class Bar
{
public int PropertyBar { get; set; }
}
2)的用户控制
public partial class UserControl : UserControl
{
public List<Bar> Bars
{
get { return Session["Bars"] as List<Bar>; }
set { Session["Bars"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bars.Add(new Bar { PropertyBar = Bars.Last().PropertyBar+1});
}
}
}
3)与该用户控件和一个按钮aspx页:
public partial class _Default : Page
{
public List<Bar> Bars
{
get
{
var foo = Session["Foo"] as Foo;
if (foo != null)
{
return foo.Bars;
}
return null;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var foo = new Foo(new List<Bar>{new Bar{PropertyBar = 1}, new Bar{PropertyBar = 2}});
Session["Foo"] = foo;
userControl.Bars = foo.Bars;
}
else
{
Bars.Add(new Bar { PropertyBar = 5 });
}
}
protected void OnButton1Click(object sender, EventArgs e)
{
label.Text = string.Format("Default.aspx has {0} bars ({1}); UserControl has {2} bars ({3})",
Bars.Count, Bars.Aggregate(string.Empty, (s, i) => s + i.PropertyBar + ",").TrimEnd(','),
userControl.Bars.Count, userControl.Bars.Aggregate(string.Empty, (s, i) => s + i.PropertyBar + ",").TrimEnd(','));
}
}
使用此:
<sessionState mode="SQLServer" timeout="20" allowCustomSqlDatabase="true"
sqlConnectionString="Data Source=.;Initial Catalog=SessionDB;User Id=XXX;Password=YYY;" />
我按下按钮,结果是:
Default.aspx has 5 bars (1,2,3,4,5); UserControl has 4 bars (1,2,3,4)
但是,如果我用这个:
<!--<sessionState mode="SQLServer" timeout="20" allowCustomSqlDatabase="true"
sqlConnectionString="Data Source=.;Initial Catalog=SessionDB;User Id=XXX;Password=YYY;" /> -->
我按下按钮,结果是:
Default.aspx has 5 bars (1,2,3,4,5); UserControl has 5 bars (1,2,3,4,5)
我的问题是:
1)为什么仅当会话的模式是“SqlServer”时才会出现此行为?
2)我应该如何正确使用本例中的会话?