[转]Invalid character in a Base-64 string

时间:2021-11-09 18:31:06

Invalid character in a Base-64 string (ASP.NET)

Filed under: ASP.NET 2.0, programming — delroger @ 11:16 am

Just came across a very peculiar problem with a website I’m developing. Some visitors to the website hit an error every time they click one of the controls on a particular page; the page loads fine the first time, but any sort of postback triggers the error. The message is:

Invalid character in a Base-64 string

and the stack trace is:

at System.Convert.FromBase64String(String s) at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) at System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) at System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState) at System.Web.UI.HiddenFieldPageStatePersister.Load()

The problem seems to be with the ViewState. The ViewState is encrypted, and when an attempt is made to decrypt it on postback, the error is triggered.  The solution is actually quite simple: in the web.config file, set the ViewState not to be encrypted, like this:

<system.web>
 <pages viewStateEncryptionMode=”Never”>
 </pages>
</system.web>

 

OK, the error is no longer produced, but why is it there in the first place?  The page works perfectly well for some visitors, but not others – and that’s when the setup is exactly the same (Windows XP, IE 7) and the same requests are going to the server.  So what’s in the ViewState for different users that is creating the problem?  Still trying to find out…

As an addendum to this post one week on, I did work out why the encryption of the ViewState was a problem.  There was quite a lot of data being stored in the ViewState: above a certain length the ViewState decryption cuts off, and therefore the string doesn’t appear like a valid one for decryption.  You can solve this by splitting the ViewState into several sections using the MaxPageStateFieldLength in the pages tag in web.config – see this post for instance:

http://weblogs.asp.net/lduveau/archive/2007/04/17/viewstate-chunking-in-asp-net-2-0-maxpagestatefieldlength.aspx

Therefore, if you want to maintain encryption on your ViewState, that’s a slightly better solution for you. Personally, I’m not convinced it matters greatly since if someone wants to decrypt your ViewState, it is trivial enough to do anyhow (see here http://www.pluralsight.com/community/media/p/51688.aspx for instance).