Friday, 7 April 2017

[Web Farm][Network Load Balancing] Unable to Serialize the Session State C# & VB

Do you faced a situation where you are required to host the same ASP.NET web application to multiple servers (Web Farm) to divide traffic into different servers due to high amount of traffic? Due to this, you configured the <sessionStateto use SQLServer in your web configuration file. While you are performing verification on your application, somehow you stumble upon an error as shown on the following image.


Based on the error "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 object or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode.", it basically means that when the <sessionState> is configured to use SQLServer, make sure that any object used to assign into Session must be decorated with serializable attribute.

Further read on the error, the key sentence "Type 'WebNLB.TestClass' in Assembly 'WebNLB, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.]". This tells you that you have a class name called TestClass and it doesn't have the attribute serializable. So add the serializable attribute to the TestClass.

[C#]
[Serializable]
public class TestClass
{

}

[VB]
<Serializable> Public Class TestClass

End Class

Do the same to your application. Make sure to add serializable attribute to all the classes that are used to assign into Session. Once you are done, redeploy your application to each of the servers and re-verify your application. You will notice that your application will no longer hit the error again.