Alter session state when EnableSessionState is ReadOnly

人盡茶涼 提交于 2020-06-28 03:11:19

问题


I have a (legacy) ASP .NET WebForms project, and I want to set EnableSessionState to ReadOnly wherever possible to prevent the session lock from blocking concurrent page loads by a single user.

On some pages, I actually do want to write to the session state.

Normally, you would just set EnableSessionState back to True for only those pages where you need to write to the session.

The problem is that the Page_Load event only needs to read from the session state, and the only code on the page that needs to write to the session state is a button Click event.

But EnableSessionState applies to the whole page - so if I set it back to True, the whole page suffers, even if it really only needs to write to the session in one particular event handler.

The big problem is that the code that needs to write to the session is in an event handler in the site-wide master page (it allows users to easily switch between linked accounts), so I literally wouldn't be able to set EnableSessionState to ReadOnly on any page at all!

So here's the question: is it possible to set EnableSessionState to ReadOnly in Web.config, and then override it for one single event handler?

So effectively, I want to do something like this:

void Button_Click(object sender, EventArgs e)
{
    // Change Session back to read/write mode just for this one event handler
    // Not actually possible, because IsReadOnly is itself read-only
    Session.IsReadOnly = false;

    // Now I should be able to write to the session
    Session["foo"] = "bar";
}

(Note that the sample code might run even when EnableSessionState is ReadOnly, but the session is not actually persisted... If you reload the page, the write to the session will not persist across page loads.)

I can't find any way of changing the session mode inside an event handler...

I thought maybe that I could create a new context instance or session instance or something like that where the session was read/write, but I can't find a way to get that to work either.

来源:https://stackoverflow.com/questions/45049194/alter-session-state-when-enablesessionstate-is-readonly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!