user2110845
user2110845

Reputation: 402

Server.Transfer causing Session exception

In my global I have the following code to handle when an error occurs

//[..] code goes here
  Server.Transfer("~/Error.aspx?ErrorID=" + errorId);

It used to be a Response.Redirect which worked perfectly except that it changed the url (which is why I want to use Server.Transfer)

Unfortunately, now when it tries to load the Error page, it crashes on the Masterpage when it tries to refer to the Session

HttpException:
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 \\ section in the application configuration.

I do have enableSessionState in both my config and my page.

I also found some links which suggest using Context.RewritePath - that just causes a blank page to load for me.

Using Response.Redirect works perfectly and as expected, so I assume Server.Transfer is the issue here. What is it?

EDIT Code:

protected void Application_Error(object sender, EventArgs e)
        {

            lock (_lockMe)
            {
                Exception ex = Server.GetLastError();

                if (ex != null)
                {
                    if (ex.InnerException != null)
                        ex = ex.InnerException;

                    ErrorLoggingManager.AddError(ex, new MembershipData(), ...); //etc
                }

                Server.ClearError();

                   //Some other database code for cleaning up some stuff when an error happens

                }

                try
                {
                    if (Response != null)
                    {
                        //Get the last error logged
                        MyDataContext db = new MyDataContext();
                        int errorId = db.LoggedErrors.OrderByDescending(le => le.ErrorId).Select(le => le.ErrorId).FirstOrDefault();

                        Server.Transfer("~/Error.aspx?ErrorID=" + errorId); 
                    }
                }
                catch (Exception)
                {
                }
            }

Upvotes: 17

Views: 4586

Answers (9)

Mike
Mike

Reputation: 71

Here's what the problem is:

If there is a page render exception (ex. "File Not Found") then Server.Transfer screws up the session. This has something to do with it being called during the page render.

As long as you are not appending headers before the error occurs, Response.Redirect will work just fine; if you are, however, using Response.AppendHeader then Response.Redirect will not work during a page render.

Try using HttpContext.Current.RewritePath instead. That should fix all these problems. For whatever reason, RewritePath() does not care that the page hasn't finished rendering.

Upvotes: 1

Mayank Pathak
Mayank Pathak

Reputation: 3681

As you have not posted much code. So without seeing the actual implementation you have done. I could suggest you below points.

Point 1. First of all, you need to check if SessionState is enabled for pages. You could set them globally in web.config file. Try the snippet given below in web.config

<configuration>   
   <system.web>
   <pages enableSessionState="true" />
  </system.web>
</configuration>

Point 2. And put your Redirection in Application_Error in Global.asax.

public void Application_Error(object sender, EventArgs e)
{
     HttpApplication app = (HttpApplication)sender;
     app.Server.Transfer("~/Error.aspx?ErrorID=" + errorId,true);
 }

Point 3. Also check if your SessionStateis set properly in IIS too.

Details are on MSDN to enable sessionstate

Hope this helps..!!!

Upvotes: 2

Ted
Ted

Reputation: 7251

You don't mention what version of ASP.NET you are using, but there were some changes between 2.0 and 3.5 in how unhandled exceptions bubbled their way up through an ASP.NET web app and then IIS.

Among some other possibles, while you are clearing the error you are not setting Context.Response.TrySkipIisCustomErrors = true; While this particular flag could have nothing to do with your issue (and is only available for 3.5+), it also could help deal with what is potentially two error pages behind the scenes that are obscuring the real issue. Regardless, it'll save you a lot of grief (at least if you are running 3.5+) with other potential issues. Check out two posts I wrote several years back that may be helpful: while they don't cover session handling, they do cover the multiple song-and-dance routines I had to follow to get proper 500 and 404 handling in various versions of ASP.NET. It's possible you will run into something that will get you further ahead, if not all the way there.

http://www.andornot.com/blog/post/Errors-Sending-the-Right-Message-(Redux-Covering-ASPNET-3540).aspx

http://www.andornot.com/blog/post/Errors-Sending-the-Right-Message.aspx

Upvotes: 0

warwickf
warwickf

Reputation: 123

From what I understand, Server.Transfer sends the content of another page to the client rather than the requested content. If that is the case, then I am wondering if it does not have something to do with applying a master page to the error page? I had a similar error years ago with earlier technology and it turned out that the master page did not like what I was trying to do.

I hope this helps at least point to a solution.

Upvotes: 1

ronilk
ronilk

Reputation: 372

@user2110845 : I had faced similar problem few months ago. the problem was with having an underscore in the website name. We were deploying a website in IIS with two different host names(adding two entries through the 'Edit Bindings' option on the website). The host names provided were abc_ts, abc_is. When the underscore was removed then the session problem got resolved. It seems there are certain characters not allowed in a website host name. Check if that is your problem. I found the answer here : link (check 'update 2' in the article)

Upvotes: 0

iamkrillin
iamkrillin

Reputation: 6876

The error you are encountering is because you are using a query string parameter. Per the msdn docs

However, the path parameter must not contain a query string, or ASP returns an error.

http://msdn.microsoft.com/en-us/library/ms525800%28v=vs.90%29.aspx

Its about 3/4 of the way down the page just above Requirements.

Even though the docs here are mentioning asp. and not asp.net, keep in mind the session state is a feature of IIS and is handled before asp.net is ever called.

Upvotes: 0

Why don't you try like this:

The Server.Transfer method also has a second parameter—"preserveForm". If you set this to True, using a statement such as Server.Transfer("WebForm2.aspx", True), the existing query string and any form variables will still be available to the page you are transferring to.

So I think doing like this your session will not expire.

Server.Transfer("~/Error.aspx?ErrorID=" + errorId,True);

Upvotes: 0

rla4
rla4

Reputation: 1246

I had the same problem in a different context a while ago. I don't know if it is your case, but if you're using IIS7 on Windows 2008, in addition to setting enableSessionState=true in your web.config, you have to put your modules inside the <system.webServer> section, instead of <system.web>. Changing this little thing solved it for me.

Upvotes: 0

Joe
Joe

Reputation: 1669

why not just use customErrors in web.config to do the redirect?

<customErrors mode="Off" defaultRedirect="~/Common/Error.aspx">
  <error statusCode="403" redirect="~/SM_AccessDenied.aspx" />
  <error statusCode="404" redirect="~/Common/FileNotFound.aspx" />
</customErrors>

Upvotes: 0

Related Questions