我发现会话模式为" SQLServer"时出现问题。 我已在以下示例中隔离了该问题:
在使用.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)为什么只有在会话模式为&#34; SqlServer&#34;?
时才会出现这种情况2)我应该如何正确使用本例中的会话?
答案 0 :(得分:0)
我对问题2的回答是:
public interface IHasBars
{
List<Bar> Bars { get; }
}
public partial class _Default : Page, IHasBars
{
//...
}
public partial class UserControl : UserControl
{
private List<Bar> bars;
private List<Bar> Bars
{
get
{
if (bars==null)
{
var hasBars = Page as IHasBars;
if (hasBars != null)
{
return bars = hasBars.Bars;
}
throw new InvalidOperationException("You can only use this userControl inside a IHasBars");
}
return bars;
}
}
//...
这样总是使用相同的列表。但我仍然不明白为什么不然。