Server.Transfer causing Session exception
Asked Answered
B

9

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)
                {
                }
            }
Beardsley answered 14/2, 2014 at 14:14 Comment(12)
can you provide exception...Dement
It's an HttpException with the details being the quoted block of textBeardsley
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...Proposition
If I put a breakpoint before the Server.Transfer, I actually have Session before it happens. The error I was testing with happens OnInit.Beardsley
Do you have session state enabled on your Error.aspx page?Statist
@RichardDeeming - yes. And in the web.config tooBeardsley
Where's the code that tries to access SessionState? And where, in context, is that code running?Dramatist
You tried this? <pages enableSessionState="true" ...> #7794279Tshombe
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" msdn.microsoft.com/en-us/library/ms525800%28v=vs.90%29.aspxAlumna
Added some additional code on how the Server.Transfer is being executed.Beardsley
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.Paramo
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.Paramo
B
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..!!!

Bestialize answered 19/2, 2014 at 8:40 Comment(6)
I added the code in the original post. Point1 - I already did that. Point2 - I'm already doing that. Point 3 - Already checked that.Beardsley
Did you set 2nd parameter to true in Server.Transfer ??Bestialize
I tried that and it made no difference. Session state mode is InProcBeardsley
Did you check response from server using fiddler...??Bestialize
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.Beardsley
Can you try to use the failed request tracing tool to see where does the error come from? It is a 5min setup and can help a lot..It will trace the requests over IISBestialize
H
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.

Hollingsworth answered 20/2, 2014 at 5:2 Comment(1)
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.Beardsley
Y
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.

York answered 9/11, 2015 at 20:43 Comment(0)
E
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>
Enugu answered 18/2, 2014 at 17:57 Comment(4)
Because I need to do some other things when an error occurs including logging. So it'll have to remain in the Application_ErrorBeardsley
You could still do that other processing in Application_Error, and just let the config handle the redirection part.Enugu
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.Beardsley
HTH! #343514Enugu
S
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.

Speller answered 18/2, 2014 at 17:57 Comment(1)
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.Beardsley
S
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);
Soiree answered 19/2, 2014 at 11:9 Comment(1)
Tried that. Made no difference.Beardsley
A
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.

Alumna answered 20/2, 2014 at 4:34 Comment(1)
I removed the Querystring parameter in the Server.Transfer - still got the same errorBeardsley
K
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)

Kalgoorlie answered 20/2, 2014 at 4:49 Comment(1)
No underscores in our website name.Beardsley
L
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

Lilialiliaceous answered 25/2, 2014 at 8:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.