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)我應該如何正確使用本例中的會話?