Translate

Monday, July 1, 2013

Fix the Session Null with Url Rewriting in asp.net

Symptoms:

Some times when you are doing some URL rewriting in asp.net , you came a cross a strange situation , your Session Property inside your pages becomes null.

The Code:

Public Sub Init(context As HttpApplication) Implements IHttpModule.Init
        AddHandler context.BeginRequest, AddressOf OnBeginRequest
End Sub
 
Public Sub OnBeginRequest(ByVal sender As Object, ByVal e As EventArgs)
        Dim app As HttpApplication = CType(sender, HttpApplication)
        If app.Context.Request.RawUrl.ToLower().Contains(".aspx")
           Then
            If Not app.Context.Request.RawUrl = "/" Then
                Dim PageId As String = PathsLayer.GetPageId(app.Context.Request.RawUrl)
                app.Context.RewritePath("~/Pages/viewpage.aspx?pageID=" 
                                        + PageId, False)
            End If
        End If
 End Sub

When you try to access the session variable inside your page after the rewriting completes you can see the following error :

Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the <configuration>\<system.web>\<httpModules> section in the application configuration.

 Solution :

The solution was to add the following 2 lines to web.config inside <system.webserver> under the <modules> section 

<remove name="Session" />
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>

and that did the trick , hope this helps some body.

No comments:

Post a Comment