Session is null in HttpHandler

Last I was working on a project and had the following scenario. There was a form on localhost:8081 where 2 parameters were filled in.
The action for this form was localhost/eventHandler

In the eventHandler I used the PreRequestHandlerExecute method to execute my code. Here I wanted to put one of the parameters into the session.
The problem was that my session was null (System.Web.HttpException: Session state is not available in this context).
This problem was solved very fast because I was forgotten to put the following code in the web.config:

<sessionState mode="InProc" timeout="60" cookieless="false"></sessionState>

After this change everything worked for a while but at a certain point it stopped working again. The session was null again.
And here I spend a lot of time searching for the problem.
The problem was not the httpHandler but the form where it all starts.
First my form code looked like this:

<form name=”testform” action=”http://localhost/” method=”POST”>
    <input type=”text” name=”inputparameter1” />
    <input type=”text” name=”inputparameter2” />
    <input type=”submit” value=”button” />
</form>

First I tried to create the session myself but this was not possible.
After a while I discovered that the action url needs to be a .aspx page. If your forms action is the url to a folder the session in the code behind will be null. If the action is an .aspx page there is already a session created.
So I needed to change the action of the form like this:

<form name=”testform” action=”http://localhost/default.aspx” method=”POST”>
    <input type=”text” name=”inputparameter1” />
    <input type=”text” name=”inputparameter2” />
    <input type=”submit” value=”button” />
</form>

Leave a Reply

Your email address will not be published. Required fields are marked *