'Unable to serialize the session state' in ASP.NET: why it happens and how to fix it
The error appears when an application that worked with the default in-process session state is switched to StateServer or SQL Server session state, typically on a hosting plan or a web farm. Out-of-process session state has to turn every object you stored into bytes, and at least one of your objects cannot be turned into bytes.
The message
Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET
will serialize the session state objects, and as a result non-serializable objects or
MarshalByRef objects are not permitted. The same restriction applies if similar
serialization is done by the custom session state store in 'Custom' mode.
[SerializationException: Type 'Shop.Cart' in Assembly 'Shop, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=null' is not marked as serializable.]
The inner SerializationException names the guilty type. Read it first: it may be your class, or a type referenced by one of its fields.
Why it only happens in some modes
| Mode (web.config) | Where data lives | Objects serialised? |
|---|---|---|
InProc (default) | Memory of the worker process | No; references are kept as they are |
StateServer | The ASP.NET State Service, a separate process or machine | Yes, at the end of each request |
SQLServer | A SQL Server database | Yes |
Custom | Your provider (for example a Redis provider) | Yes, in practice |
So the bug was always there; in-process state hid it. You will see the error after:
- moving to a host that configures StateServer or SQL Server state;
- scaling out to several servers, which requires shared state;
- a colleague switching modes to keep sessions across application pool recycles.
The configuration looks like this:
<system.web>
<sessionState mode="StateServer"
stateConnectionString="tcpip=127.0.0.1:42424"
timeout="20" />
</system.web>
Fix 1: mark your classes as serializable
Session state uses binary serialisation (BinaryFormatter through the session state serialiser), which requires the [Serializable] attribute on every class in the object graph, including base classes and field types:
using System;
using System.Collections.Generic;
[Serializable]
public class Cart
{
public List<CartLine> Lines { get; } = new List<CartLine>();
public string CouponCode { get; set; }
public decimal Total()
{
decimal total = 0;
foreach (var line in Lines) total += line.UnitPrice * line.Quantity;
return total;
}
}
[Serializable]
public class CartLine
{
public int ProductId { get; set; }
public string Name { get; set; }
public decimal UnitPrice { get; set; }
public int Quantity { get; set; }
}
Auto-implemented properties are fine: their compiler-generated backing fields are serialised. Events are a trap: a class with an event serialises its subscribers too, which often drags in a page or control. Mark such fields with [field: NonSerialized].
Fix 2: exclude what should not travel
Some fields are caches or handles that make no sense outside the current process. Mark them [NonSerialized] and rebuild them when needed:
[Serializable]
public class CustomerContext
{
public int CustomerId { get; set; }
[NonSerialized]
private Customer _customer; // loaded on demand, not stored
public Customer GetCustomer(ICustomerRepository repo)
{
if (_customer == null)
{
_customer = repo.Find(CustomerId);
}
return _customer;
}
}
[NonSerialized] applies to fields, not properties. After deserialisation the field holds its default value (null here), which is why the getter reloads it.
Fix 3: never store these in session
Some objects can never be serialised meaningfully, and storing them in session is a design problem even in InProc mode:
SqlConnection,SqlDataReader, open streams and file handles;- pages, user controls and web controls (
Page,GridView,TextBox…); HttpContext,HttpRequest,HttpResponse;- Entity Framework
DbContextinstances, and entity proxies attached to one; - anonymous types and LINQ query objects (an
IQueryableis a query, not data).
Store the data you need, not the object that produced it: an id, a small DTO, a list of values.
Fix 4: store less
Serialisation cost is paid on every request that uses session, in both directions. Large objects, such as a whole DataSet of search results, slow every page. A lean pattern:
// Store the key...
Session["CustomerId"] = customer.Id;
// ...and reload when needed
int id = (int)Session["CustomerId"];
Customer c = repository.Find(id);
DataTable and DataSet are serialisable, so they do not cause this error, but they are heavy. If you must keep search results, store the criteria and rerun the query, or keep the ids only.
Finding the offending object
When the exception names a framework type (for example System.Data.SqlClient.SqlConnection), you need to know which session key holds a reference to it. Test each entry at the end of a request in a development build:
// Global.asax.cs - development diagnostics only
// BinaryFormatter is obsolete; use this only to reproduce what the session serialiser does.
protected void Application_PostRequestHandlerExecute(object sender, EventArgs e)
{
var session = HttpContext.Current?.Session;
if (session == null) return;
foreach (string key in session.Keys)
{
object value = session[key];
if (value == null) continue;
try
{
using (var ms = new System.IO.MemoryStream())
{
#pragma warning disable SYSLIB0011
new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter().Serialize(ms, value);
#pragma warning restore SYSLIB0011
}
}
catch (System.Runtime.Serialization.SerializationException ex)
{
System.Diagnostics.Debug.WriteLine("Session key '" + key + "': " + ex.Message);
}
}
}
The #pragma lines only matter if the project is compiled with newer tooling that flags BinaryFormatter; on .NET Framework 4.8 it still works. Remove the diagnostic before release.
A note on security
Binary serialisation is dangerous when it reads untrusted data, which is why Microsoft marked BinaryFormatter obsolete in modern .NET. Session data written and read by your own state server is trusted, but keep the state server and the session database reachable only by your web servers, and do not reuse BinaryFormatter elsewhere in your code for data that comes from users.
ASP.NET Core
ASP.NET Core does not store objects in session at all: ISession stores byte arrays and strings (SetString, SetInt32). You serialise objects yourself, usually to JSON with System.Text.Json, which avoids this class of error entirely. If you are porting a Web Forms app, convert session objects to small JSON-friendly types.
See also Session state vs ViewState and Parser Error when deploying.
Official documentation
- Microsoft Learn: Session-state modes
- Microsoft Learn: SerializableAttribute and NonSerializedAttribute
- Microsoft Learn: BinaryFormatter security guide
- Microsoft Learn: Session and state management in ASP.NET Core