Preserve Session State when using Server.Transfer in Sitecore
The title of this post is a little misleading, the solution doesn't use Server.Transfer, it provides an alternate solution involving the Sitecore.Web.WebUtil.RewriteUrl() method which relies on HttpContext.RewritePath() method.
This solution may not fit the purpose for everyone or every purpose, but here goes:
This - as far as I can tell - needs to be in the httpRequestBegin pipeline before the page starts rendering. For my purpose, I was trying to use the Sitecore setting RequestErrors.UseServerSideRedirect=true so the url of the requested item doesn't change on a 404 error (ItemNotFound). I needed to override the PerformRedirect method in Sitecore.Pipelines.HttpRequest.ExecuteRequest class. To do so I created a new class that would be replacing this one in the httpRequestBegin pipeline. However, you don't need to replace the Sitecore.Pipelines.HttpRequest.ExecuteRequest class, you can create your own process and add it to the end of the httpRequestBegin pipeline.
public class ExecuteRequest : Sitecore.Pipelines.HttpRequest.ExecuteRequest
{
protected override void PerformRedirect(string url)
{
if (Settings.RequestErrors.UseServerSideRedirect)
{
Sitecore.Web.WebUtil.RewriteUrl(url);
}
else
{
WebUtil.Redirect(url, false);
}
}
}
Note that this will only work if the URL is to an .aspx page and in the page load method set the Sitecore.Context.Item to whichever item you'd like. This solution will not work for Sitecore Items.
If you'd like to server side redirect to a Sitecore Item, please find out how to do that here.
Now you have to replace the in the web.config, you can do it by modifying the web.config directly OR if you're like me and would like to keep the web.config file as close to the release version as possible, then you can add a .config file to the /App_Config/Include folder with something similar to the below XML.
your.namespace.ExecuteRequest, yourAssembly
Now the page you previously tried to Server.Transfer to that didn't have state, now has session state!