My session key is a const string variable. See below.
On first Page Load, I add a string to the session using this key. I also indicate to KeepAlive on the key on the first load and every PostBack. However, on PostBack, I notice that the key is no longer in the session.
I found that to fix this, I simply have to remove "const" from the variable, and everything works fine.
Can someone explain and provide any educational resources on why this is happening.
private const string ENTITY_KEY = "c335a928-72ac-4403-b5f8-418f1e5ac1ec";
public string CurrentEntity
{
get { WebClientSession.Current[ENTITY_KEY] as string); }
set { WebClientSession.Current.AddTransient(ENTITY_KEY, value); }
}
protected void Page_Load(object sender, System.EventArgs e)
{
string key = (string)Request["Id"] + "";
CurrentEntity = Mapper.Lookup.FindById(key);
WebClientSession.Current.KeepAlive(ENTITY_KEY);
}
private void _bindGrid()
{
...
// CurrentEntity is null here on PostBack. Good on first load.
...
}
I am not sure what WebClientSession
is but the HttpSessionState
will work with const
. There is no reason why it should not work. Here is the proof that it will work:
private const string ENTITY_KEY = "c335a928-72ac-4403-b5f8-418f1e5ac1ec";
protected void Page_Load(object sender, EventArgs e) {
if( !this.IsPostBack ) {
Session.Add( "ENTITY_KEY", ENTITY_KEY );
}
}
protected void Button1_Click(object sender, EventArgs e) {
string s = Session[ "ENTITY_KEY" ].ToString();
}
I simply added a button to my form. In the load method if the page is being requested I added a const
variable's contents to the Session
. In the click handler of the button, which is the form being posted, I access it from the Session
and it is there.
So why is it not working for you?
There are 2 possible reasons:
Reason 1
The issue is in your WebClientSession
class. I do not know the details of that class so cannot say what the issue is.
Reason 2
Session
is stored in memory on the server. So, if this site is deployed on a farm, it is possible that the server which served the page initially added the ENTITY_KEY
to Session
. But when the page is posted back on the button click, another server serves the request. This server may not have the ENTITY_KEY
in its memory since it is possible it has never served that page yet. In a web farm, you would want to use another source to store session related data such as a database or a file etc.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.