17

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)
                {
                }
            }
user2110845
  • 552
  • 7
  • 17
  • can you provide exception... – Pranay Rana Feb 14 '14 at 14:20
  • It's an HttpException with the details being the quoted block of text – user2110845 Feb 14 '14 at 14:22
  • 1
    Some wild guest, your error throw is happening somewhere on the header reads, so with your transfer that headers can not be readed again, and the cookie is not loaded (from the browser client), so is fail to connect it with the session... so no session on this error... – Aristos Feb 14 '14 at 14:26
  • If I put a breakpoint before the Server.Transfer, I actually have Session before it happens. The error I was testing with happens OnInit. – user2110845 Feb 14 '14 at 14:34
  • Do you have session state enabled on your `Error.aspx` page? – Richard Deeming Feb 14 '14 at 15:31
  • @RichardDeeming - yes. And in the web.config too – user2110845 Feb 17 '14 at 08:40
  • Where's the code that tries to access `SessionState`? And where, in context, is that code running? – Mike Perrenoud Feb 18 '14 at 17:59
  • You tried this? http://stackoverflow.com/questions/7793779/sessions-lost-during-server-transfer-in-asp-net – Newse Feb 18 '14 at 18:11
  • Without seeing some of the code, I dont know there is much we can do to help. Server.Transfer() does not cause the session to be lost. "This means that any variables or objects that have been assigned a value in session or application scope are maintained" http://msdn.microsoft.com/en-us/library/ms525800%28v=vs.90%29.aspx – iamkrillin Feb 18 '14 at 19:14
  • Added some additional code on how the Server.Transfer is being executed. – user2110845 Feb 19 '14 at 11:06
  • I got the same problem on an error handler and I cannot access the session after `Server.Transfer` when the initial exception (that called the error handler) is a `HttpException` that is thrown by the IIS, not my own code (i.e. real 404). On all other exceptions, the session is still accessible without any error after `Server.Transfer`. – Martin Braun May 17 '15 at 13:27
  • `HttpContext.Current.Session` won't throw any exception, but it will be null in that case. It's better to check, but won't help when sessions are required on the error page. – Martin Braun May 17 '15 at 14:24

9 Answers9

2

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..!!!

Crystal Meth
  • 571
  • 1
  • 4
  • 16
Mayank Pathak
  • 3,453
  • 5
  • 35
  • 63
  • I added the code in the original post. Point1 - I already did that. Point2 - I'm already doing that. Point 3 - Already checked that. – user2110845 Feb 19 '14 at 11:02
  • Did you set 2nd parameter to true in `Server.Transfer` ?? – Mayank Pathak Feb 19 '14 at 11:14
  • I tried that and it made no difference. Session state mode is InProc – user2110845 Feb 19 '14 at 13:23
  • Did you check response from server using fiddler...?? – Mayank Pathak Feb 21 '14 at 04:23
  • Response from server is a blank page with a 200 (OK) message. Content-Lenght is 0. Request headers pass the session cookie correctly. Not sure what I'm looking for. – user2110845 Feb 21 '14 at 10:25
  • Can you try to use the [failed request tracing tool](http://www.iis.net/learn/extensions/url-rewrite-module/using-failed-request-tracing-to-trace-rewrite-rules) to see where does the error come from? It is a 5min setup and can help a lot..It will trace the requests over IIS – Mayank Pathak Feb 21 '14 at 12:44
1

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.

warwickf
  • 123
  • 6
  • I've never had any issues with the MasterPage and other Server.Transfers. I can't remove the MasterPage from the error page otherwise for obvious reasons. – user2110845 Feb 20 '14 at 08:46
1

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.

Mike
  • 71
  • 1
  • 2
0

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>
Joe
  • 1,489
  • 10
  • 9
  • Because I need to do some other things when an error occurs including logging. So it'll have to remain in the Application_Error – user2110845 Feb 19 '14 at 11:02
  • You could still do that other processing in Application_Error, and just let the config handle the redirection part. – Joe Feb 19 '14 at 14:13
  • How would I return the ErrorID in the redirection ? The ErrorID in this context is not the status code but an internal id that the user needs to use to report the error itself. – user2110845 Feb 19 '14 at 14:18
  • HTH! http://stackoverflow.com/questions/343014/asp-net-custom-error-page-server-getlasterror-is-null – Joe Feb 19 '14 at 14:45
0

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.

rla4
  • 1,148
  • 1
  • 13
  • 25
  • This is also happening on the Visual Studio Development server in Windows 8. The code itself has been hosted on IIS7 on Windows 08 for a few years now and never had problems with session state except for this current issue. – user2110845 Feb 19 '14 at 11:05
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);
ch.smrutiranjan parida
  • 2,302
  • 4
  • 25
  • 38
0

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.

iamkrillin
  • 6,656
  • 1
  • 21
  • 49
0

@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)

ronilk
  • 183
  • 3
  • 13
0

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

Ted
  • 6,898
  • 8
  • 45
  • 73