System.Security.Claims .ClaimsIdentity.WriteTo() has a bug

Getting “cannot read past the end of the stream” when trying to use System.Security.ClaimsIdentity.WriteTo() to store a claims identity. Disassembled it:

// System.Security.Claims.ClaimsIdentity
protected virtual void WriteTo(BinaryWriter writer, byte[] userData)
{
	if (writer == null)
	{
		throw new ArgumentNullException("writer");
	}
	int num = 0;
	ClaimsIdentity.SerializationMask serializationMask = ClaimsIdentity.SerializationMask.None;
        ... get flags here...
	writer.Write((int)serializationMask);
	writer.Write(num);
	if ((serializationMask & ClaimsIdentity.SerializationMask.AuthenticationType) == ClaimsIdentity.SerializationMask.AuthenticationType)
	{
		writer.Write(this.m_authenticationType);
	}
        ...
	if ((serializationMask & ClaimsIdentity.SerializationMask.HasClaims) == ClaimsIdentity.SerializationMask.HasClaims)
	{
		writer.Write(this.m_instanceClaims.Count);
		using (List<Claim>.Enumerator enumerator = this.m_instanceClaims.GetEnumerator())
		{
			while (enumerator.MoveNext())
			{
				enumerator.Current.WriteTo(writer);
			}
		}
	}
        ...
	writer.Flush();
}

It writes the flags, then the number of fields, then some of the other values, then the number of claims, then the claims, then some more fields.

On the other hand, the constructor doesn’t read the number of fields, just starts reading the fields (but not Label) and then the claims, and then doesn’t read the rest of the fields.

// System.Security.Claims.ClaimsIdentity
private void Initialize(BinaryReader reader)
{
	if (reader == null)
	{
		throw new ArgumentNullException("reader");
	}
	int expr_14 = reader.ReadInt32();
	if ((expr_14 & 1) == 1)
	{
		this.m_authenticationType = reader.ReadString();
	}
	if ((expr_14 & 2) == 2)
	{
		this.m_bootstrapContext = reader.ReadString();
	}
	if ((expr_14 & 4) == 4)
	{
		this.m_nameType = reader.ReadString();
	}
	else
	{
		this.m_nameType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name";
	}
	if ((expr_14 & 8) == 8)
	{
		this.m_roleType = reader.ReadString();
	}
	else
	{
		this.m_roleType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role";
	}
	if ((expr_14 & 16) == 16)
	{
		int num = reader.ReadInt32();
		for (int i = 0; i < num; i++)
		{
			Claim item = new Claim(reader, this);
			this.m_instanceClaims.Add(item);
		}
	}
}