Resolving “HttpContextWrapper is not serializable” errors after upgrading Glimpse.

If you are doing any ASP.NET development and not using Glimpse you are seriously missing out. It helps is so many ways to troubleshoot and improve performance that I cannot believe how I’ve done any web development without in the past. I’m really grateful for the work that it has been done by the developers.

However, today I decided to update all the NuGet packages I thought they were safe and as you would have guessed it, the update broke my MVC4 website. A simple MVC website will probably not come across this issue, but I have added some code to intercept all application errors and exceptions and redirect to an error page where a meaningful message can be displayed. The code that does the interception within the Application_Error method in Global.asax is listed below:

var lastError = Server.GetLastError();
Server.ClearError();

var statusCode = lastError.GetType() == typeof(HttpException) ? ((HttpException)lastError).GetHttpCode() : 500;
var routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action", "Index");
routeData.Values.Add("statusCode", statusCode);
routeData.Values.Add("exception", lastError);
IController controller = new ErrorController();

var requestContext = new RequestContext(new HttpContextWrapper(Context), routeData);

controller.Execute(requestContext);

The line that started failing is isolated. If you try to run the code you will be confronted with the following exception:

An unhandled System.Runtime.Serialization.SerializationException exception occurred while processing the request Type 'System.Web.HttpContextWrapper' in assembly 'System.Web.Abstractions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' is not marked as serializable.
at Microsoft.VisualStudio.WebHost.Host.ProcessRequest(Connection conn) at Microsoft.VisualStudio.WebHost.Server.OnSocketAccept(Object acceptedSocket)
Version Information: ASP.NET Development Server 11.0.0.0

It seems that this is bug that has slipped to the latest update as per the original thread on Github here. Depending on how you are using HttpContextWrapper in your implementation, there may be a few ways to bypass the current bug, but for me the simplest solution was to switch from using the VS2012 Development Server for debugging to IIS Express.

I hope this helps anyone else coming across this issue.

Happy coding...


  • Share this post on