473,749 Members | 2,486 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Viewstate issues after move to 2.0 from 1.1

I have an app that was originally 1.1, now migrated to 2.0 and have run into
some sporadic viewstate errors...usuall y saying the viewstate is invalid,
eventvalidation failed or mac error.

My web config does specify a machinekey setting:

<machineKey
validationKey=" 447C05E8B3A7140 1CC4CAE5513A7F1 A3494A3618EE819 316AAD1D58433F2 36A759D66FB4154 500E01EB4E1BC1D E42046E2D652D39 1CB8367A1649438 867A02EB"
decryptionKey=" CE8D47C43312A14 4B49DE5E8D3D3CA 2CDEA230077AFB8 6CB"
validation="SHA 1"/>

The errors are occuring during some custom code that i wrote that saves form
data when a user's login times out and restores it by reposting it after the
user logs in.

Specifically, in the global.asax file there is a function as below
(truncated to shorten). When the user's session times out from inactivity,
the entire request.form object (all posted data) is saved in the cache with a
key saved as a cookie on the user's machine.

Sub Application_Aut henticateReques t(ByVal sender As Object, ByVal e As
EventArgs)
' Fires upon attempting to authenticate the user
If (Request.IsAuth enticated) Then
............... .........
ElseIf (Request.Form.C ount > 0 AndAlso
(Request.Cookie s("widsplusform key") Is Nothing OrElse
Request.Cookies ("widsplusformk ey").Value = "") AndAlso Request.Path.To Lower
<> "/widsplus/login.aspx" AndAlso Request.Path.To Lower <> "login.aspx ") Then
Dim guidstring As String = Guid.NewGuid.To String

' Save any posted form data
System.Web.Http Context.Current .Cache.Add(guid string,
Request.Form, Nothing, Now.AddMinutes( 16), Cache.NoSliding Expiration,
Caching.CacheIt emPriority.Norm al, Nothing)
' save cookie with guid string
Response.Cookie s("widsplusform key").Value = guidstring
Response.Cookie s("widsplusform key").Path = "/widsplus"
Response.Cookie s("widsplusform key").Expires =
Now().AddMinute s(15)
End If
End Sub

Next, on the logon page, once the user is authenticated, it redirects
manually to another page called "formredirect.a spx". The code on that page
(below) custom generates a page reconstructing the form data and then posting
it to the original page the user was on. This preserves the form data so the
user can continue from where they left off.

This process worked 100% fine in ASP.NET 1.1. It is only once the
application was migrated to 2.0 that the errors began. And they only happen
part of the time and almost seem related to the amount of form data that
needs to be reposted?

Any ideas how to correct or why the errors only occur part of the time etc.
I will probably try turning off eventvalidation to see if that is the reason
since it is difference i can see in the data that is posted back.
(Code for formredirect.as px - aspx file is blank and the below generates all
of the html).

Public Sub OutputFormData( )
Response.Write( "<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0
Transitional//EN""
""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d"">" + Chr(10))
Response.Write( "<html lang=""en"">" + Chr(10))
Response.Write( " <head>" + Chr(10))
Response.Write( " <title>See Spot Reload the Form!!!</title>" +
Chr(10))
Response.Write( " </head>" + Chr(10))
Response.Write( " <body bgcolor=""#ffff ff"">" + Chr(10))
Response.Write( " <div id=""showprogre ss"" style=""DISPLAY :
inline; VISIBILITY: visible; WIDTH: 100%; POSITION: absolute"">" + Chr(10))
Response.Write( " <p align=""center" "><img
src=""globalima ges/transp.gif"" width=""5"" height=""50"">< br>" + Chr(10))
Response.Write( " <font face=""verdana" " size=""4""
color=""#ffcc66 ""><b>Resubmitt ing Original Request...Pleas e
Wait...</b></font><br><br>" + Chr(10))
Response.Write( " <img
src=""globalima ges/progressbarslow er.gif""><br>" + Chr(10))
Response.Write( " <font face=""verdana" " color=""#dddddd ""
size=""1"">This may take a few moments...</font><br><br>" + Chr(10))
Response.Write( " <a href=""mainmenu .aspx""><font
face=""verdana" " size=""2"" color=""#ffcc66 ""><b>Cance l & Return to Main
Menu</b></font></a></p></div>" + Chr(10))

If (Not (Request.Cookie s("widsplusform key") Is Nothing) AndAlso
Request.Cookies ("widsplusformk ey").Value <> "" AndAlso Not
(System.Web.Htt pContext.Curren t.Cache(Request .Cookies("widsp lusformkey").Va lue) Is Nothing)) Then
Dim rf As Specialized.Nam eValueCollectio n =
CType(System.We b.HttpContext.C urrent.Cache(Re quest.Cookies(" widsplusformkey ").Value), Specialized.Nam eValueCollectio n)

Response.Flush( )
If Not (rf Is Nothing) Then
Response.Write( "<form name=""Form1"" method=""post""
action=""" + FormsAuthentica tion.GetRedirec tUrl(User.Ident ity.Name, False) +
""" id=""Form1"">" + Chr(10))
For i As Integer = 0 To rf.Count - 1
Response.Write( "<input type=""hidden"" name=""" +
rf.GetKey(i) + """ id=""" + rf.GetKey(i) + """ value=""" + rf.Item(i) + """>"
+ Chr(10))
Next
Response.Write( "</form>" + Chr(10) + "<script
language=javasc ript>" + Chr(10) + "window.documen t.forms['Form1'].submit()" +
Chr(10) + "</script>" + Chr(10))
Response.Write( " </body>")
Response.Write( "</html>")
' clear the saved post data

System.Web.Http Context.Current .Cache.Remove(R equest.Cookies( "widsplusformke y").Value)
Response.Cookie s("widsplusform key").Value = ""
Response.Cookie s("widsplusform key").Path = "/widsplus"
End If
Else
Response.Write( " </body>")
Response.Write( "</html>")
Response.Cookie s("widsplusform key").Value = ""
Response.Cookie s("widsplusform key").Path = "/widsplus"

Response.Redire ct(FormsAuthent ication.GetRedi rectUrl(User.Id entity.Name,
False))
End If
End Sub
Nov 23 '05 #1
10 3090
Some more info.

I turned of "eventvalidatio n" (enableeventval idation=false in web.config)
and that appears to prevent the errors although since they are sporadic i
can't be 100% sure for a couple of days.

So then my question becomes what exactly triggers "event validation" to
return an error? What exactly is it checking?

I prefer not to disable security features so i'd prefer to fix my
redirection function so it doesn't trigger the error rather than disable
event validation.

"Robert" wrote:
I have an app that was originally 1.1, now migrated to 2.0 and have run into
some sporadic viewstate errors...usuall y saying the viewstate is invalid,
eventvalidation failed or mac error.

My web config does specify a machinekey setting:

<machineKey
validationKey=" 447C05E8B3A7140 1CC4CAE5513A7F1 A3494A3618EE819 316AAD1D58433F2 36A759D66FB4154 500E01EB4E1BC1D E42046E2D652D39 1CB8367A1649438 867A02EB"
decryptionKey=" CE8D47C43312A14 4B49DE5E8D3D3CA 2CDEA230077AFB8 6CB"
validation="SHA 1"/>

The errors are occuring during some custom code that i wrote that saves form
data when a user's login times out and restores it by reposting it after the
user logs in.

Specifically, in the global.asax file there is a function as below
(truncated to shorten). When the user's session times out from inactivity,
the entire request.form object (all posted data) is saved in the cache with a
key saved as a cookie on the user's machine.

Sub Application_Aut henticateReques t(ByVal sender As Object, ByVal e As
EventArgs)
' Fires upon attempting to authenticate the user
If (Request.IsAuth enticated) Then
............... .........
ElseIf (Request.Form.C ount > 0 AndAlso
(Request.Cookie s("widsplusform key") Is Nothing OrElse
Request.Cookies ("widsplusformk ey").Value = "") AndAlso Request.Path.To Lower
<> "/widsplus/login.aspx" AndAlso Request.Path.To Lower <> "login.aspx ") Then
Dim guidstring As String = Guid.NewGuid.To String

' Save any posted form data
System.Web.Http Context.Current .Cache.Add(guid string,
Request.Form, Nothing, Now.AddMinutes( 16), Cache.NoSliding Expiration,
Caching.CacheIt emPriority.Norm al, Nothing)
' save cookie with guid string
Response.Cookie s("widsplusform key").Value = guidstring
Response.Cookie s("widsplusform key").Path = "/widsplus"
Response.Cookie s("widsplusform key").Expires =
Now().AddMinute s(15)
End If
End Sub

Next, on the logon page, once the user is authenticated, it redirects
manually to another page called "formredirect.a spx". The code on that page
(below) custom generates a page reconstructing the form data and then posting
it to the original page the user was on. This preserves the form data so the
user can continue from where they left off.

This process worked 100% fine in ASP.NET 1.1. It is only once the
application was migrated to 2.0 that the errors began. And they only happen
part of the time and almost seem related to the amount of form data that
needs to be reposted?

Any ideas how to correct or why the errors only occur part of the time etc.
I will probably try turning off eventvalidation to see if that is the reason
since it is difference i can see in the data that is posted back.
(Code for formredirect.as px - aspx file is blank and the below generates all
of the html).

Public Sub OutputFormData( )
Response.Write( "<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0
Transitional//EN""
""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d"">" + Chr(10))
Response.Write( "<html lang=""en"">" + Chr(10))
Response.Write( " <head>" + Chr(10))
Response.Write( " <title>See Spot Reload the Form!!!</title>" +
Chr(10))
Response.Write( " </head>" + Chr(10))
Response.Write( " <body bgcolor=""#ffff ff"">" + Chr(10))
Response.Write( " <div id=""showprogre ss"" style=""DISPLAY :
inline; VISIBILITY: visible; WIDTH: 100%; POSITION: absolute"">" + Chr(10))
Response.Write( " <p align=""center" "><img
src=""globalima ges/transp.gif"" width=""5"" height=""50"">< br>" + Chr(10))
Response.Write( " <font face=""verdana" " size=""4""
color=""#ffcc66 ""><b>Resubmitt ing Original Request...Pleas e
Wait...</b></font><br><br>" + Chr(10))
Response.Write( " <img
src=""globalima ges/progressbarslow er.gif""><br>" + Chr(10))
Response.Write( " <font face=""verdana" " color=""#dddddd ""
size=""1"">This may take a few moments...</font><br><br>" + Chr(10))
Response.Write( " <a href=""mainmenu .aspx""><font
face=""verdana" " size=""2"" color=""#ffcc66 ""><b>Cance l & Return to Main
Menu</b></font></a></p></div>" + Chr(10))

If (Not (Request.Cookie s("widsplusform key") Is Nothing) AndAlso
Request.Cookies ("widsplusformk ey").Value <> "" AndAlso Not
(System.Web.Htt pContext.Curren t.Cache(Request .Cookies("widsp lusformkey").Va lue) Is Nothing)) Then
Dim rf As Specialized.Nam eValueCollectio n =
CType(System.We b.HttpContext.C urrent.Cache(Re quest.Cookies(" widsplusformkey ").Value), Specialized.Nam eValueCollectio n)

Response.Flush( )
If Not (rf Is Nothing) Then
Response.Write( "<form name=""Form1"" method=""post""
action=""" + FormsAuthentica tion.GetRedirec tUrl(User.Ident ity.Name, False) +
""" id=""Form1"">" + Chr(10))
For i As Integer = 0 To rf.Count - 1
Response.Write( "<input type=""hidden"" name=""" +
rf.GetKey(i) + """ id=""" + rf.GetKey(i) + """ value=""" + rf.Item(i) + """>"
+ Chr(10))
Next
Response.Write( "</form>" + Chr(10) + "<script
language=javasc ript>" + Chr(10) + "window.documen t.forms['Form1'].submit()" +
Chr(10) + "</script>" + Chr(10))
Response.Write( " </body>")
Response.Write( "</html>")
' clear the saved post data

System.Web.Http Context.Current .Cache.Remove(R equest.Cookies( "widsplusformke y").Value)
Response.Cookie s("widsplusform key").Value = ""
Response.Cookie s("widsplusform key").Path = "/widsplus"
End If
Else
Response.Write( " </body>")
Response.Write( "</html>")
Response.Cookie s("widsplusform key").Value = ""
Response.Cookie s("widsplusform key").Path = "/widsplus"

Response.Redire ct(FormsAuthent ication.GetRedi rectUrl(User.Id entity.Name,
False))
End If
End Sub

Nov 23 '05 #2
Hi Robert,

I think the problem you got is because your code simulated the steps taken
by a hacker who might want to violate the security of your site. ASP.NET 2.0
attempts to ensure that all postback requests were triggered by code rendered
from the page’s server side controls (during the previous request). In other
words, ASP.NET validates View State to verify that it came from the correct
page, but your code in the method OutputFormData in formredirect.as px wrote
everything including the ("<!DOCTYPE> ” from scratch.

I would suggest that you turn on back again the enableeventvali dation and
re-program the page named "formredirect.a spx" to use the page controls
collection to add content within the form instead of the Response.Write
method to write an html form to the browser.

Let ASP.NET handles its ViewState to ensure the security of your site.

--
HTH,
Phillip Williams
http://www.societopia.net
http://www.webswapp.com
"Robert" wrote:
Some more info.

I turned of "eventvalidatio n" (enableeventval idation=false in web.config)
and that appears to prevent the errors although since they are sporadic i
can't be 100% sure for a couple of days.

So then my question becomes what exactly triggers "event validation" to
return an error? What exactly is it checking?

I prefer not to disable security features so i'd prefer to fix my
redirection function so it doesn't trigger the error rather than disable
event validation.

"Robert" wrote:
I have an app that was originally 1.1, now migrated to 2.0 and have run into
some sporadic viewstate errors...usuall y saying the viewstate is invalid,
eventvalidation failed or mac error.

My web config does specify a machinekey setting:

<machineKey
validationKey=" 447C05E8B3A7140 1CC4CAE5513A7F1 A3494A3618EE819 316AAD1D58433F2 36A759D66FB4154 500E01EB4E1BC1D E42046E2D652D39 1CB8367A1649438 867A02EB"
decryptionKey=" CE8D47C43312A14 4B49DE5E8D3D3CA 2CDEA230077AFB8 6CB"
validation="SHA 1"/>

The errors are occuring during some custom code that i wrote that saves form
data when a user's login times out and restores it by reposting it after the
user logs in.

Specifically, in the global.asax file there is a function as below
(truncated to shorten). When the user's session times out from inactivity,
the entire request.form object (all posted data) is saved in the cache with a
key saved as a cookie on the user's machine.

Sub Application_Aut henticateReques t(ByVal sender As Object, ByVal e As
EventArgs)
' Fires upon attempting to authenticate the user
If (Request.IsAuth enticated) Then
............... .........
ElseIf (Request.Form.C ount > 0 AndAlso
(Request.Cookie s("widsplusform key") Is Nothing OrElse
Request.Cookies ("widsplusformk ey").Value = "") AndAlso Request.Path.To Lower
<> "/widsplus/login.aspx" AndAlso Request.Path.To Lower <> "login.aspx ") Then
Dim guidstring As String = Guid.NewGuid.To String

' Save any posted form data
System.Web.Http Context.Current .Cache.Add(guid string,
Request.Form, Nothing, Now.AddMinutes( 16), Cache.NoSliding Expiration,
Caching.CacheIt emPriority.Norm al, Nothing)
' save cookie with guid string
Response.Cookie s("widsplusform key").Value = guidstring
Response.Cookie s("widsplusform key").Path = "/widsplus"
Response.Cookie s("widsplusform key").Expires =
Now().AddMinute s(15)
End If
End Sub

Next, on the logon page, once the user is authenticated, it redirects
manually to another page called "formredirect.a spx". The code on that page
(below) custom generates a page reconstructing the form data and then posting
it to the original page the user was on. This preserves the form data so the
user can continue from where they left off.

This process worked 100% fine in ASP.NET 1.1. It is only once the
application was migrated to 2.0 that the errors began. And they only happen
part of the time and almost seem related to the amount of form data that
needs to be reposted?

Any ideas how to correct or why the errors only occur part of the time etc.
I will probably try turning off eventvalidation to see if that is the reason
since it is difference i can see in the data that is posted back.
(Code for formredirect.as px - aspx file is blank and the below generates all
of the html).

Public Sub OutputFormData( )
Response.Write( "<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0
Transitional//EN""
""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d"">" + Chr(10))
Response.Write( "<html lang=""en"">" + Chr(10))
Response.Write( " <head>" + Chr(10))
Response.Write( " <title>See Spot Reload the Form!!!</title>" +
Chr(10))
Response.Write( " </head>" + Chr(10))
Response.Write( " <body bgcolor=""#ffff ff"">" + Chr(10))
Response.Write( " <div id=""showprogre ss"" style=""DISPLAY :
inline; VISIBILITY: visible; WIDTH: 100%; POSITION: absolute"">" + Chr(10))
Response.Write( " <p align=""center" "><img
src=""globalima ges/transp.gif"" width=""5"" height=""50"">< br>" + Chr(10))
Response.Write( " <font face=""verdana" " size=""4""
color=""#ffcc66 ""><b>Resubmitt ing Original Request...Pleas e
Wait...</b></font><br><br>" + Chr(10))
Response.Write( " <img
src=""globalima ges/progressbarslow er.gif""><br>" + Chr(10))
Response.Write( " <font face=""verdana" " color=""#dddddd ""
size=""1"">This may take a few moments...</font><br><br>" + Chr(10))
Response.Write( " <a href=""mainmenu .aspx""><font
face=""verdana" " size=""2"" color=""#ffcc66 ""><b>Cance l & Return to Main
Menu</b></font></a></p></div>" + Chr(10))

If (Not (Request.Cookie s("widsplusform key") Is Nothing) AndAlso
Request.Cookies ("widsplusformk ey").Value <> "" AndAlso Not
(System.Web.Htt pContext.Curren t.Cache(Request .Cookies("widsp lusformkey").Va lue) Is Nothing)) Then
Dim rf As Specialized.Nam eValueCollectio n =
CType(System.We b.HttpContext.C urrent.Cache(Re quest.Cookies(" widsplusformkey ").Value), Specialized.Nam eValueCollectio n)

Response.Flush( )
If Not (rf Is Nothing) Then
Response.Write( "<form name=""Form1"" method=""post""
action=""" + FormsAuthentica tion.GetRedirec tUrl(User.Ident ity.Name, False) +
""" id=""Form1"">" + Chr(10))
For i As Integer = 0 To rf.Count - 1
Response.Write( "<input type=""hidden"" name=""" +
rf.GetKey(i) + """ id=""" + rf.GetKey(i) + """ value=""" + rf.Item(i) + """>"
+ Chr(10))
Next
Response.Write( "</form>" + Chr(10) + "<script
language=javasc ript>" + Chr(10) + "window.documen t.forms['Form1'].submit()" +
Chr(10) + "</script>" + Chr(10))
Response.Write( " </body>")
Response.Write( "</html>")
' clear the saved post data

System.Web.Http Context.Current .Cache.Remove(R equest.Cookies( "widsplusformke y").Value)
Response.Cookie s("widsplusform key").Value = ""
Response.Cookie s("widsplusform key").Path = "/widsplus"
End If
Else
Response.Write( " </body>")
Response.Write( "</html>")
Response.Cookie s("widsplusform key").Value = ""
Response.Cookie s("widsplusform key").Path = "/widsplus"

Response.Redire ct(FormsAuthent ication.GetRedi rectUrl(User.Id entity.Name,
False))
End If
End Sub

Nov 23 '05 #3
Hi Philip,

Your suggestion was an interesting one and so i implemented it (code is
below). However, I still receive the same viewstate error. I tried having
the page not output viewstate itself. I tried having it output viewstate on
its own. It tried suppressing the original viewstate and i tried not
suppressing it.

In all cases I still get the error. Any other ideas/suggestions re the code
below?

What I'm suspecting is that either of the two below is ultimately
responsible for the error:

1) Because the type of the form controls i generate doesn't match the
original type (obviously i can't tell what the original type was...)
2) and/or the url of the page is being used to validate (the url
formredirection .aspx is not the same as the original).

Because this is in intranet site and didn't originally under 1.1 have event
validation I can probably just set this to false in the web config.

But i agree that ideally I would want to leave it on which is why i'm
spending considerable time trying to figure out a way around this.

Thx.
R-

Code for "formredirectio n.aspx":

<%@ Page Language="vb" EnableViewState ="false" EnableEventVali dation="false"
ValidateRequest =false AutoEventWireup ="false"
Inherits="WIDSP LUS.NET.formred irection2" CodeFile="formr edirection2.asp x.vb"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>See Spot Reload the Form!!!</title>
</head>
<body bgcolor="#fffff f">
<form runat="server">
</form>
</body>
</html>

Code behind:

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArg s) Handles MyBase.Load
'Put user code to initialize the page here
If (Not (Request.Cookie s("widsplusform key") Is Nothing) AndAlso
Request.Cookies ("widsplusformk ey").Value <> "" AndAlso Not
(System.Web.Htt pContext.Curren t.Cache(Request .Cookies("widsp lusformkey").Va lue) Is Nothing)) Then
Dim rf As Specialized.Nam eValueCollectio n =
CType(System.We b.HttpContext.C urrent.Cache(Re quest.Cookies(" widsplusformkey ").Value), Specialized.Nam eValueCollectio n)

If Not (rf Is Nothing) Then
' Clear the saved post data

System.Web.Http Context.Current .Cache.Remove(R equest.Cookies( "widsplusformke y").Value)
' Clear cookies
Response.Cookie s("widsplusform key").Value = ""
Response.Cookie s("widsplusform key").Path = "/widsplus"
' Output progress indicator
Response.Write( "<div id=""showprogre ss""
style=""DISPLAY : inline; VISIBILITY: visible; WIDTH: 100%; POSITION:
absolute"">" + Chr(10))
Response.Write( " <p align=""center" "><img
src=""globalima ges/transp.gif"" width=""5"" height=""50"">< br>" + Chr(10))
Response.Write( " <font face=""verdana" " size=""4""
color=""#ffcc66 ""><b>Resubmitt ing Original Request...Pleas e
Wait...</b></font><br><br>" + Chr(10))
Response.Write( " <img
src=""globalima ges/progressbarslow er.gif""><br>" + Chr(10))
Response.Write( " <font face=""verdana" "
color=""#dddddd "" size=""1"">This may take a few moments...</font><br><br>" +
Chr(10))
Response.Write( " <a href=""mainmenu .aspx""><font
face=""verdana" " size=""2"" color=""#ffcc66 ""><b>Cance l & Return to Main
Menu</b></font></a></p></div>" + Chr(10))
Response.Flush( )

' Construct form dynamically
Page.Form.ID = "Form1"
Page.Form.Name = "Form1"
Page.Form.Metho d = "post"

For i As Integer = 0 To rf.Count - 1
If (rf.GetKey(i).L ength < 2 OrElse
rf.GetKey(i).Su bstring(0, 2) <> "__") Then
Dim control As New HtmlInputHidden ()

control.Name = rf.GetKey(i)
control.ID = rf.GetKey(i)
control.Value = rf.Item(i)

Page.Form.Contr ols.Add(control )
End If
Next
ClientScript.Re gisterClientScr iptBlock(GetTyp e(String),
"postform", "<script
language=""java script"">window .document.forms['Form1'].action=""" +
FormsAuthentica tion.GetRedirec tUrl(User.Ident ity.Name, False) +
""";window.docu ment.forms['Form1'].submit();</script>")
End If
Else
Response.Cookie s("widsplusform key").Value = ""
Response.Cookie s("widsplusform key").Path = "/widsplus"

Response.Redire ct(FormsAuthent ication.GetRedi rectUrl(User.Id entity.Name,
False))
End If
End Sub

"Phillip Williams" wrote:
Hi Robert,

I think the problem you got is because your code simulated the steps taken
by a hacker who might want to violate the security of your site. ASP.NET 2.0
attempts to ensure that all postback requests were triggered by code rendered
from the page’s server side controls (during the previous request). In other
words, ASP.NET validates View State to verify that it came from the correct
page, but your code in the method OutputFormData in formredirect.as px wrote
everything including the ("<!DOCTYPE> ” from scratch.

I would suggest that you turn on back again the enableeventvali dation and
re-program the page named "formredirect.a spx" to use the page controls
collection to add content within the form instead of the Response.Write
method to write an html form to the browser.

Let ASP.NET handles its ViewState to ensure the security of your site.

--
HTH,
Phillip Williams
http://www.societopia.net
http://www.webswapp.com
"Robert" wrote:
Some more info.

I turned of "eventvalidatio n" (enableeventval idation=false in web.config)
and that appears to prevent the errors although since they are sporadic i
can't be 100% sure for a couple of days.

So then my question becomes what exactly triggers "event validation" to
return an error? What exactly is it checking?

I prefer not to disable security features so i'd prefer to fix my
redirection function so it doesn't trigger the error rather than disable
event validation.

"Robert" wrote:
I have an app that was originally 1.1, now migrated to 2.0 and have run into
some sporadic viewstate errors...usuall y saying the viewstate is invalid,
eventvalidation failed or mac error.

My web config does specify a machinekey setting:

<machineKey
validationKey=" 447C05E8B3A7140 1CC4CAE5513A7F1 A3494A3618EE819 316AAD1D58433F2 36A759D66FB4154 500E01EB4E1BC1D E42046E2D652D39 1CB8367A1649438 867A02EB"
decryptionKey=" CE8D47C43312A14 4B49DE5E8D3D3CA 2CDEA230077AFB8 6CB"
validation="SHA 1"/>

The errors are occuring during some custom code that i wrote that saves form
data when a user's login times out and restores it by reposting it after the
user logs in.

Specifically, in the global.asax file there is a function as below
(truncated to shorten). When the user's session times out from inactivity,
the entire request.form object (all posted data) is saved in the cache with a
key saved as a cookie on the user's machine.

Sub Application_Aut henticateReques t(ByVal sender As Object, ByVal e As
EventArgs)
' Fires upon attempting to authenticate the user
If (Request.IsAuth enticated) Then
............... .........
ElseIf (Request.Form.C ount > 0 AndAlso
(Request.Cookie s("widsplusform key") Is Nothing OrElse
Request.Cookies ("widsplusformk ey").Value = "") AndAlso Request.Path.To Lower
<> "/widsplus/login.aspx" AndAlso Request.Path.To Lower <> "login.aspx ") Then
Dim guidstring As String = Guid.NewGuid.To String

' Save any posted form data
System.Web.Http Context.Current .Cache.Add(guid string,
Request.Form, Nothing, Now.AddMinutes( 16), Cache.NoSliding Expiration,
Caching.CacheIt emPriority.Norm al, Nothing)
' save cookie with guid string
Response.Cookie s("widsplusform key").Value = guidstring
Response.Cookie s("widsplusform key").Path = "/widsplus"
Response.Cookie s("widsplusform key").Expires =
Now().AddMinute s(15)
End If
End Sub

Next, on the logon page, once the user is authenticated, it redirects
manually to another page called "formredirect.a spx". The code on that page
(below) custom generates a page reconstructing the form data and then posting
it to the original page the user was on. This preserves the form data so the
user can continue from where they left off.

This process worked 100% fine in ASP.NET 1.1. It is only once the
application was migrated to 2.0 that the errors began. And they only happen
part of the time and almost seem related to the amount of form data that
needs to be reposted?

Any ideas how to correct or why the errors only occur part of the time etc.
I will probably try turning off eventvalidation to see if that is the reason
since it is difference i can see in the data that is posted back.
(Code for formredirect.as px - aspx file is blank and the below generates all
of the html).

Public Sub OutputFormData( )
Response.Write( "<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0
Transitional//EN""
""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d"">" + Chr(10))
Response.Write( "<html lang=""en"">" + Chr(10))
Response.Write( " <head>" + Chr(10))
Response.Write( " <title>See Spot Reload the Form!!!</title>" +
Chr(10))
Response.Write( " </head>" + Chr(10))
Response.Write( " <body bgcolor=""#ffff ff"">" + Chr(10))
Response.Write( " <div id=""showprogre ss"" style=""DISPLAY :
inline; VISIBILITY: visible; WIDTH: 100%; POSITION: absolute"">" + Chr(10))
Response.Write( " <p align=""center" "><img
src=""globalima ges/transp.gif"" width=""5"" height=""50"">< br>" + Chr(10))
Response.Write( " <font face=""verdana" " size=""4""
color=""#ffcc66 ""><b>Resubmitt ing Original Request...Pleas e
Wait...</b></font><br><br>" + Chr(10))
Response.Write( " <img
src=""globalima ges/progressbarslow er.gif""><br>" + Chr(10))
Response.Write( " <font face=""verdana" " color=""#dddddd ""
size=""1"">This may take a few moments...</font><br><br>" + Chr(10))
Response.Write( " <a href=""mainmenu .aspx""><font
face=""verdana" " size=""2"" color=""#ffcc66 ""><b>Cance l & Return to Main
Menu</b></font></a></p></div>" + Chr(10))

If (Not (Request.Cookie s("widsplusform key") Is Nothing) AndAlso
Request.Cookies ("widsplusformk ey").Value <> "" AndAlso Not
(System.Web.Htt pContext.Curren t.Cache(Request .Cookies("widsp lusformkey").Va lue) Is Nothing)) Then
Dim rf As Specialized.Nam eValueCollectio n =
CType(System.We b.HttpContext.C urrent.Cache(Re quest.Cookies(" widsplusformkey ").Value), Specialized.Nam eValueCollectio n)

Response.Flush( )
If Not (rf Is Nothing) Then
Response.Write( "<form name=""Form1"" method=""post""
action=""" + FormsAuthentica tion.GetRedirec tUrl(User.Ident ity.Name, False) +
""" id=""Form1"">" + Chr(10))
For i As Integer = 0 To rf.Count - 1
Response.Write( "<input type=""hidden"" name=""" +
rf.GetKey(i) + """ id=""" + rf.GetKey(i) + """ value=""" + rf.Item(i) + """>"
+ Chr(10))
Next
Response.Write( "</form>" + Chr(10) + "<script
language=javasc ript>" + Chr(10) + "window.documen t.forms['Form1'].submit()" +
Chr(10) + "</script>" + Chr(10))
Response.Write( " </body>")
Response.Write( "</html>")
' clear the saved post data

System.Web.Http Context.Current .Cache.Remove(R equest.Cookies( "widsplusformke y").Value)
Response.Cookie s("widsplusform key").Value = ""
Response.Cookie s("widsplusform key").Path = "/widsplus"
End If
Else
Response.Write( " </body>")
Response.Write( "</html>")
Response.Cookie s("widsplusform key").Value = ""
Response.Cookie s("widsplusform key").Path = "/widsplus"

Response.Redire ct(FormsAuthent ication.GetRedi rectUrl(User.Id entity.Name,
False))
End If
End Sub

Nov 24 '05 #4
Thanks for Phillip's inputs,

Hi Robert,

I think Phillip's description on this is reasonable. Based on the document
of the EnableEventVali dation setting:

=============
ASP.NET controls create client-side script to raise post-back events on the
server. Because a malicious user could use the postback script to send
arbitrary post events to server controls, ASP.NET 2.0 controls validate the
event data to ensure the event was raised by client-side code rendered by
the control.
=============

the ASP.NET 2.0 by default will check the postback datas so as to ensure
all the form elements(contro ls) are generated and rendered by the asp.net
page's control structure rather than manually injected by clientside
user(scripts... ). So in your scenario, you use Response.Write to manually
generate the page's content (output html form elements....) which is not
under the control of ASP.NET page control structure, so we'll get such
exception when post back....

As Phillip has suggested, if possible, we'd recommend that we redesign the
page so as to avoid such manual page rendering...

Thanks,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
--------------------
| Thread-Topic: Viewstate issues after move to 2.0 from 1.1
| thread-index: AcXwWoXmdxcbpXh TQrqsDjsXYR0hNw ==
| X-WBNR-Posting-Host: 64.253.156.46
| From: "=?Utf-8?B?UGhpbGxpcCB XaWxsaWFtcw==?= "
<Ph************ **@webswapp.com >
| References: <82************ *************** *******@microso ft.com>
<C3************ *************** *******@microso ft.com>
| Subject: RE: Viewstate issues after move to 2.0 from 1.1
| Date: Wed, 23 Nov 2005 10:20:03 -0800
| Lines: 165
| Message-ID: <C6************ *************** *******@microso ft.com>
| MIME-Version: 1.0
| Content-Type: text/plain;
| charset="Utf-8"
| Content-Transfer-Encoding: 8bit
| X-Newsreader: Microsoft CDO for Windows 2000
| Content-Class: urn:content-classes:message
| Importance: normal
| Priority: normal
| X-MimeOLE: Produced By Microsoft MimeOLE V6.00.3790.0
| Newsgroups: microsoft.publi c.dotnet.framew ork.aspnet
| NNTP-Posting-Host: TK2MSFTNGXA03.p hx.gbl 10.40.2.250
| Path: TK2MSFTNGXA02.p hx.gbl!TK2MSFTN GXA03.phx.gbl
| Xref: TK2MSFTNGXA02.p hx.gbl
microsoft.publi c.dotnet.framew ork.aspnet:3605 18
| X-Tomcat-NG: microsoft.publi c.dotnet.framew ork.aspnet
|
| Hi Robert,
|
| I think the problem you got is because your code simulated the steps
taken
| by a hacker who might want to violate the security of your site. ASP.NET
2.0
| attempts to ensure that all postback requests were triggered by code
rendered
| from the page’s server side controls (during the previous request). In
other
| words, ASP.NET validates View State to verify that it came from the
correct
| page, but your code in the method OutputFormData in formredirect.as px
wrote
| everything including the ("<!DOCTYPE>? from scratch.
|
| I would suggest that you turn on back again the enableeventvali dation and
| re-program the page named "formredirect.a spx" to use the page controls
| collection to add content within the form instead of the Response.Write
| method to write an html form to the browser.
|
| Let ASP.NET handles its ViewState to ensure the security of your site.
|
| --
| HTH,
| Phillip Williams
| http://www.societopia.net
| http://www.webswapp.com
|
|
| "Robert" wrote:
|
| > Some more info.
| >
| > I turned of "eventvalidatio n" (enableeventval idation=false in
web.config)
| > and that appears to prevent the errors although since they are sporadic
i
| > can't be 100% sure for a couple of days.
| >
| > So then my question becomes what exactly triggers "event validation" to
| > return an error? What exactly is it checking?
| >
| > I prefer not to disable security features so i'd prefer to fix my
| > redirection function so it doesn't trigger the error rather than
disable
| > event validation.
| >
| > "Robert" wrote:
| >
| > > I have an app that was originally 1.1, now migrated to 2.0 and have
run into
| > > some sporadic viewstate errors...usuall y saying the viewstate is
invalid,
| > > eventvalidation failed or mac error.
| > >
| > > My web config does specify a machinekey setting:
| > >
| > > <machineKey
| > >
validationKey=" 447C05E8B3A7140 1CC4CAE5513A7F1 A3494A3618EE819 316AAD1D58433F2 3
6A759D66FB41545 00E01EB4E1BC1DE 42046E2D652D391 CB8367A16494388 67A02EB"
| > > decryptionKey=" CE8D47C43312A14 4B49DE5E8D3D3CA 2CDEA230077AFB8 6CB"
| > > validation="SHA 1"/>
| > >
| > > The errors are occuring during some custom code that i wrote that
saves form
| > > data when a user's login times out and restores it by reposting it
after the
| > > user logs in.
| > >
| > > Specifically, in the global.asax file there is a function as below
| > > (truncated to shorten). When the user's session times out from
inactivity,
| > > the entire request.form object (all posted data) is saved in the
cache with a
| > > key saved as a cookie on the user's machine.
| > >
| > > Sub Application_Aut henticateReques t(ByVal sender As Object, ByVal e
As
| > > EventArgs)
| > > ' Fires upon attempting to authenticate the user
| > > If (Request.IsAuth enticated) Then
| > > ............... .........
| > > ElseIf (Request.Form.C ount > 0 AndAlso
| > > (Request.Cookie s("widsplusform key") Is Nothing OrElse
| > > Request.Cookies ("widsplusformk ey").Value = "") AndAlso
Request.Path.To Lower
| > > <> "/widsplus/login.aspx" AndAlso Request.Path.To Lower <>
"login.aspx ") Then
| > > Dim guidstring As String = Guid.NewGuid.To String
| > >
| > > ' Save any posted form data
| > > System.Web.Http Context.Current .Cache.Add(guid string,
| > > Request.Form, Nothing, Now.AddMinutes( 16), Cache.NoSliding Expiration,
| > > Caching.CacheIt emPriority.Norm al, Nothing)
| > > ' save cookie with guid string
| > > Response.Cookie s("widsplusform key").Value = guidstring
| > > Response.Cookie s("widsplusform key").Path = "/widsplus"
| > > Response.Cookie s("widsplusform key").Expires =
| > > Now().AddMinute s(15)
| > > End If
| > > End Sub
| > >
| > > Next, on the logon page, once the user is authenticated, it redirects
| > > manually to another page called "formredirect.a spx". The code on
that page
| > > (below) custom generates a page reconstructing the form data and then
posting
| > > it to the original page the user was on. This preserves the form
data so the
| > > user can continue from where they left off.
| > >
| > > This process worked 100% fine in ASP.NET 1.1. It is only once the
| > > application was migrated to 2.0 that the errors began. And they only
happen
| > > part of the time and almost seem related to the amount of form data
that
| > > needs to be reposted?
| > >
| > > Any ideas how to correct or why the errors only occur part of the
time etc.
| > > I will probably try turning off eventvalidation to see if that is the
reason
| > > since it is difference i can see in the data that is posted back.
| > >
| > >
| > > (Code for formredirect.as px - aspx file is blank and the below
generates all
| > > of the html).
| > >
| > > Public Sub OutputFormData( )
| > > Response.Write( "<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML
1.0
| > > Transitional//EN""
| > > ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d"">" +
Chr(10))
| > > Response.Write( "<html lang=""en"">" + Chr(10))
| > > Response.Write( " <head>" + Chr(10))
| > > Response.Write( " <title>See Spot Reload the
Form!!!</title>" +
| > > Chr(10))
| > > Response.Write( " </head>" + Chr(10))
| > > Response.Write( " <body bgcolor=""#ffff ff"">" + Chr(10))
| > > Response.Write( " <div id=""showprogre ss""
style=""DISPLAY :
| > > inline; VISIBILITY: visible; WIDTH: 100%; POSITION: absolute"">" +
Chr(10))
| > > Response.Write( " <p align=""center" "><img
| > > src=""globalima ges/transp.gif"" width=""5"" height=""50"">< br>" +
Chr(10))
| > > Response.Write( " <font face=""verdana" " size=""4""
| > > color=""#ffcc66 ""><b>Resubmitt ing Original Request...Pleas e
| > > Wait...</b></font><br><br>" + Chr(10))
| > > Response.Write( " <img
| > > src=""globalima ges/progressbarslow er.gif""><br>" + Chr(10))
| > > Response.Write( " <font face=""verdana" "
color=""#dddddd ""
| > > size=""1"">This may take a few moments...</font><br><br>" + Chr(10))
| > > Response.Write( " <a href=""mainmenu .aspx""><font
| > > face=""verdana" " size=""2"" color=""#ffcc66 ""><b>Cance l & Return to
Main
| > > Menu</b></font></a></p></div>" + Chr(10))
| > >
| > > If (Not (Request.Cookie s("widsplusform key") Is Nothing)
AndAlso
| > > Request.Cookies ("widsplusformk ey").Value <> "" AndAlso Not
| > >
(System.Web.Htt pContext.Curren t.Cache(Request .Cookies("widsp lusformkey").Va l
ue) Is Nothing)) Then
| > > Dim rf As Specialized.Nam eValueCollectio n =
| > >
CType(System.We b.HttpContext.C urrent.Cache(Re quest.Cookies(" widsplusformkey "
).Value), Specialized.Nam eValueCollectio n)
| > >
| > > Response.Flush( )
| > > If Not (rf Is Nothing) Then
| > > Response.Write( "<form name=""Form1""
method=""post""
| > > action=""" + FormsAuthentica tion.GetRedirec tUrl(User.Ident ity.Name,
False) +
| > > """ id=""Form1"">" + Chr(10))
| > > For i As Integer = 0 To rf.Count - 1
| > > Response.Write( "<input type=""hidden""
name=""" +
| > > rf.GetKey(i) + """ id=""" + rf.GetKey(i) + """ value=""" + rf.Item(i)
+ """>"
| > > + Chr(10))
| > > Next
| > > Response.Write( "</form>" + Chr(10) + "<script
| > > language=javasc ript>" + Chr(10) +
"window.documen t.forms['Form1'].submit()" +
| > > Chr(10) + "</script>" + Chr(10))
| > > Response.Write( " </body>")
| > > Response.Write( "</html>")
| > > ' clear the saved post data
| > >
| > >
System.Web.Http Context.Current .Cache.Remove(R equest.Cookies( "widsplusformke y
").Value)
| > > Response.Cookie s("widsplusform key").Value = ""
| > > Response.Cookie s("widsplusform key").Path =
"/widsplus"
| > > End If
| > > Else
| > > Response.Write( " </body>")
| > > Response.Write( "</html>")
| > > Response.Cookie s("widsplusform key").Value = ""
| > > Response.Cookie s("widsplusform key").Path = "/widsplus"
| > >
| > >
Response.Redire ct(FormsAuthent ication.GetRedi rectUrl(User.Id entity.Name,
| > > False))
| > > End If
| > > End Sub
|

Nov 24 '05 #5
Hi Steven,

I agree that this is a better, cleaner approach. In my response, i tried
this however and am still receiving the error. So I'm unsure what I am doing
wrong or if there is a way to do this that will work.

Thx.
R-

"Steven Cheng[MSFT]" wrote:
Thanks for Phillip's inputs,

Hi Robert,

I think Phillip's description on this is reasonable. Based on the document
of the EnableEventVali dation setting:

=============
ASP.NET controls create client-side script to raise post-back events on the
server. Because a malicious user could use the postback script to send
arbitrary post events to server controls, ASP.NET 2.0 controls validate the
event data to ensure the event was raised by client-side code rendered by
the control.
=============

the ASP.NET 2.0 by default will check the postback datas so as to ensure
all the form elements(contro ls) are generated and rendered by the asp.net
page's control structure rather than manually injected by clientside
user(scripts... ). So in your scenario, you use Response.Write to manually
generate the page's content (output html form elements....) which is not
under the control of ASP.NET page control structure, so we'll get such
exception when post back....

As Phillip has suggested, if possible, we'd recommend that we redesign the
page so as to avoid such manual page rendering...

Thanks,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
--------------------
| Thread-Topic: Viewstate issues after move to 2.0 from 1.1
| thread-index: AcXwWoXmdxcbpXh TQrqsDjsXYR0hNw ==
| X-WBNR-Posting-Host: 64.253.156.46
| From: "=?Utf-8?B?UGhpbGxpcCB XaWxsaWFtcw==?= "
<Ph************ **@webswapp.com >
| References: <82************ *************** *******@microso ft.com>
<C3************ *************** *******@microso ft.com>
| Subject: RE: Viewstate issues after move to 2.0 from 1.1
| Date: Wed, 23 Nov 2005 10:20:03 -0800
| Lines: 165
| Message-ID: <C6************ *************** *******@microso ft.com>
| MIME-Version: 1.0
| Content-Type: text/plain;
| charset="Utf-8"
| Content-Transfer-Encoding: 8bit
| X-Newsreader: Microsoft CDO for Windows 2000
| Content-Class: urn:content-classes:message
| Importance: normal
| Priority: normal
| X-MimeOLE: Produced By Microsoft MimeOLE V6.00.3790.0
| Newsgroups: microsoft.publi c.dotnet.framew ork.aspnet
| NNTP-Posting-Host: TK2MSFTNGXA03.p hx.gbl 10.40.2.250
| Path: TK2MSFTNGXA02.p hx.gbl!TK2MSFTN GXA03.phx.gbl
| Xref: TK2MSFTNGXA02.p hx.gbl
microsoft.publi c.dotnet.framew ork.aspnet:3605 18
| X-Tomcat-NG: microsoft.publi c.dotnet.framew ork.aspnet
|
| Hi Robert,
|
| I think the problem you got is because your code simulated the steps
taken
| by a hacker who might want to violate the security of your site. ASP.NET
2.0
| attempts to ensure that all postback requests were triggered by code
rendered
| from the page’s server side controls (during the previous request). In
other
| words, ASP.NET validates View State to verify that it came from the
correct
| page, but your code in the method OutputFormData in formredirect.as px
wrote
| everything including the ("<!DOCTYPE>â ?from scratch.
|
| I would suggest that you turn on back again the enableeventvali dation and
| re-program the page named "formredirect.a spx" to use the page controls
| collection to add content within the form instead of the Response.Write
| method to write an html form to the browser.
|
| Let ASP.NET handles its ViewState to ensure the security of your site.
|
| --
| HTH,
| Phillip Williams
| http://www.societopia.net
| http://www.webswapp.com
|
|
| "Robert" wrote:
|
| > Some more info.
| >
| > I turned of "eventvalidatio n" (enableeventval idation=false in
web.config)
| > and that appears to prevent the errors although since they are sporadic
i
| > can't be 100% sure for a couple of days.
| >
| > So then my question becomes what exactly triggers "event validation" to
| > return an error? What exactly is it checking?
| >
| > I prefer not to disable security features so i'd prefer to fix my
| > redirection function so it doesn't trigger the error rather than
disable
| > event validation.
| >
| > "Robert" wrote:
| >
| > > I have an app that was originally 1.1, now migrated to 2.0 and have
run into
| > > some sporadic viewstate errors...usuall y saying the viewstate is
invalid,
| > > eventvalidation failed or mac error.
| > >
| > > My web config does specify a machinekey setting:
| > >
| > > <machineKey
| > >
validationKey=" 447C05E8B3A7140 1CC4CAE5513A7F1 A3494A3618EE819 316AAD1D58433F2 3
6A759D66FB41545 00E01EB4E1BC1DE 42046E2D652D391 CB8367A16494388 67A02EB"
| > > decryptionKey=" CE8D47C43312A14 4B49DE5E8D3D3CA 2CDEA230077AFB8 6CB"
| > > validation="SHA 1"/>
| > >
| > > The errors are occuring during some custom code that i wrote that
saves form
| > > data when a user's login times out and restores it by reposting it
after the
| > > user logs in.
| > >
| > > Specifically, in the global.asax file there is a function as below
| > > (truncated to shorten). When the user's session times out from
inactivity,
| > > the entire request.form object (all posted data) is saved in the
cache with a
| > > key saved as a cookie on the user's machine.
| > >
| > > Sub Application_Aut henticateReques t(ByVal sender As Object, ByVal e
As
| > > EventArgs)
| > > ' Fires upon attempting to authenticate the user
| > > If (Request.IsAuth enticated) Then
| > > ............... .........
| > > ElseIf (Request.Form.C ount > 0 AndAlso
| > > (Request.Cookie s("widsplusform key") Is Nothing OrElse
| > > Request.Cookies ("widsplusformk ey").Value = "") AndAlso
Request.Path.To Lower
| > > <> "/widsplus/login.aspx" AndAlso Request.Path.To Lower <>
"login.aspx ") Then
| > > Dim guidstring As String = Guid.NewGuid.To String
| > >
| > > ' Save any posted form data
| > > System.Web.Http Context.Current .Cache.Add(guid string,
| > > Request.Form, Nothing, Now.AddMinutes( 16), Cache.NoSliding Expiration,
| > > Caching.CacheIt emPriority.Norm al, Nothing)
| > > ' save cookie with guid string
| > > Response.Cookie s("widsplusform key").Value = guidstring
| > > Response.Cookie s("widsplusform key").Path = "/widsplus"
| > > Response.Cookie s("widsplusform key").Expires =
| > > Now().AddMinute s(15)
| > > End If
| > > End Sub
| > >
| > > Next, on the logon page, once the user is authenticated, it redirects
| > > manually to another page called "formredirect.a spx". The code on
that page
| > > (below) custom generates a page reconstructing the form data and then
posting
| > > it to the original page the user was on. This preserves the form
data so the
| > > user can continue from where they left off.
| > >
| > > This process worked 100% fine in ASP.NET 1.1. It is only once the
| > > application was migrated to 2.0 that the errors began. And they only
happen
| > > part of the time and almost seem related to the amount of form data
that
| > > needs to be reposted?
| > >
| > > Any ideas how to correct or why the errors only occur part of the
time etc.
| > > I will probably try turning off eventvalidation to see if that is the
reason
| > > since it is difference i can see in the data that is posted back.
| > >
| > >
| > > (Code for formredirect.as px - aspx file is blank and the below
generates all
| > > of the html).
| > >
| > > Public Sub OutputFormData( )
| > > Response.Write( "<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML
1.0
| > > Transitional//EN""
| > > ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d"">" +
Chr(10))
| > > Response.Write( "<html lang=""en"">" + Chr(10))
| > > Response.Write( " <head>" + Chr(10))
| > > Response.Write( " <title>See Spot Reload the
Form!!!</title>" +
| > > Chr(10))
| > > Response.Write( " </head>" + Chr(10))
| > > Response.Write( " <body bgcolor=""#ffff ff"">" + Chr(10))
| > > Response.Write( " <div id=""showprogre ss""
style=""DISPLAY :
| > > inline; VISIBILITY: visible; WIDTH: 100%; POSITION: absolute"">" +
Chr(10))
| > > Response.Write( " <p align=""center" "><img
| > > src=""globalima ges/transp.gif"" width=""5"" height=""50"">< br>" +
Chr(10))
| > > Response.Write( " <font face=""verdana" " size=""4""
| > > color=""#ffcc66 ""><b>Resubmitt ing Original Request...Pleas e
| > > Wait...</b></font><br><br>" + Chr(10))
| > > Response.Write( " <img
| > > src=""globalima ges/progressbarslow er.gif""><br>" + Chr(10))
| > > Response.Write( " <font face=""verdana" "
color=""#dddddd ""
| > > size=""1"">This may take a few moments...</font><br><br>" + Chr(10))
| > > Response.Write( " <a href=""mainmenu .aspx""><font
| > > face=""verdana" " size=""2"" color=""#ffcc66 ""><b>Cance l & Return to
Main
| > > Menu</b></font></a></p></div>" + Chr(10))
| > >
| > > If (Not (Request.Cookie s("widsplusform key") Is Nothing)
AndAlso
| > > Request.Cookies ("widsplusformk ey").Value <> "" AndAlso Not
| > >
(System.Web.Htt pContext.Curren t.Cache(Request .Cookies("widsp lusformkey").Va l
ue) Is Nothing)) Then
| > > Dim rf As Specialized.Nam eValueCollectio n =
| > >
CType(System.We b.HttpContext.C urrent.Cache(Re quest.Cookies(" widsplusformkey "
).Value), Specialized.Nam eValueCollectio n)
| > >
| > > Response.Flush( )
| > > If Not (rf Is Nothing) Then
| > > Response.Write( "<form name=""Form1""
method=""post""
| > > action=""" + FormsAuthentica tion.GetRedirec tUrl(User.Ident ity.Name,
False) +
| > > """ id=""Form1"">" + Chr(10))
| > > For i As Integer = 0 To rf.Count - 1
| > > Response.Write( "<input type=""hidden""
name=""" +
| > > rf.GetKey(i) + """ id=""" + rf.GetKey(i) + """ value=""" + rf.Item(i)
+ """>"
| > > + Chr(10))
| > > Next
| > > Response.Write( "</form>" + Chr(10) + "<script
| > > language=javasc ript>" + Chr(10) +
"window.documen t.forms['Form1'].submit()" +
| > > Chr(10) + "</script>" + Chr(10))
| > > Response.Write( " </body>")
| > > Response.Write( "</html>")
| > > ' clear the saved post data
| > >
| > >
System.Web.Http Context.Current .Cache.Remove(R equest.Cookies( "widsplusformke y
").Value)
| > > Response.Cookie s("widsplusform key").Value = ""
| > > Response.Cookie s("widsplusform key").Path =
"/widsplus"
| > > End If
| > > Else
| > > Response.Write( " </body>")
| > > Response.Write( "</html>")
| > > Response.Cookie s("widsplusform key").Value = ""
| > > Response.Cookie s("widsplusform key").Path = "/widsplus"
| > >
| > >
Response.Redire ct(FormsAuthent ication.GetRedi rectUrl(User.Id entity.Name,
| > > False))
| > > End If
| > > End Sub
|

Nov 24 '05 #6
Steven,

Below is the most recent revision i tried of the ASPX and codebehind for the
formredirection page.

What I've found is that if instead of having the clientside script i output
to the page change the form action value to the final page and let the page
post back to itself, then no error is returned. However, of course, this
defeats the purpose.

The moment I use the code at the end of the below where the script changes
the form action for postback to the original page (prior to the user having
timed-out), then i end up with the viewstate error.

I am unable to determine any way to get this to work with eventvalidation
turned on. This may well be by design.

I tried finding a way to dynamically turn of eventvalidation under the
theory that i could perhaps have the final destination page disable it's
eventvalidation temporarily but no property exists for this.

All combinations and modifications I've made have been unable to prevent the
error.

So I'm still left with having to just turn off eventvalidation application
wide in order to make this functionality work.

I'm a bit surprised that MS didn't look at adding this type of functionality
into ASP.NET...i.e. ability to save form data when a timeout occurs for login
and then restore it afterwards. This makes an application much more
user-friendly if you have forms that contain a fair number of fields since if
the user gets interrupted and then goes back, the data is preserved on the
server and restored by the code I wrote after the user re-logs in as opposed
to the common and standard behavior that they do get back to the same page
afterwards but with everything completely blank - all their data lost.

If anyone has suggestions on what speciifically I could change in the below
that would make it work, I'd be very grateful. But I'm getting the
impression this is a lost cause (perhaps by design).

Thx.
R-

Current Code Version:

<%@ Page Language="vb" EnableViewState ="true" EnableEventVali dation="true"
ValidateRequest =false AutoEventWireup ="false"
Inherits="WIDSP LUS.NET.formred irection2" CodeFile="formr edirection2.asp x.vb"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>See Spot Reload the Form!!!</title>
</head>
<body bgcolor="#fffff f">
<form runat="server">
</form>
</body>
</html>

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArg s) Handles MyBase.Load
'Put user code to initialize the page here
If (Page.IsPostBac k) Then
Exit Sub ' Should not ever happen
End If
If (Not (Request.Cookie s("widsplusform key") Is Nothing) AndAlso
Request.Cookies ("widsplusformk ey").Value <> "" AndAlso Not
(System.Web.Htt pContext.Curren t.Cache(Request .Cookies("widsp lusformkey").Va lue) Is Nothing)) Then
Dim rf As Specialized.Nam eValueCollectio n =
CType(System.We b.HttpContext.C urrent.Cache(Re quest.Cookies(" widsplusformkey ").Value), Specialized.Nam eValueCollectio n)

If Not (rf Is Nothing) Then
' Clear the saved post data

System.Web.Http Context.Current .Cache.Remove(R equest.Cookies( "widsplusformke y").Value)
' Clear cookies
Response.Cookie s("widsplusform key").Value = ""
Response.Cookie s("widsplusform key").Path = "/widsplus"
' Output progress indicator
Response.Write( "<div id=""showprogre ss""
style=""DISPLAY : inline; VISIBILITY: visible; WIDTH: 100%; POSITION:
absolute"">" + Chr(10))
Response.Write( " <p align=""center" "><img
src=""globalima ges/transp.gif"" width=""5"" height=""50"">< br>" + Chr(10))
Response.Write( " <font face=""verdana" " size=""4""
color=""#ffcc66 ""><b>Resubmitt ing Original Request...Pleas e
Wait...</b></font><br><br>" + Chr(10))
Response.Write( " <img
src=""globalima ges/progressbarslow er.gif""><br>" + Chr(10))
Response.Write( " <font face=""verdana" "
color=""#dddddd "" size=""1"">This may take a few moments...</font><br><br>" +
Chr(10))
Response.Write( " <a href=""mainmenu .aspx""><font
face=""verdana" " size=""2"" color=""#ffcc66 ""><b>Cance l & Return to Main
Menu</b></font></a></p></div>" + Chr(10))
Response.Flush( )

' Construct form dynamically
Page.Form.ID = "Form1"
Page.Form.Name = "Form1"
Page.Form.Metho d = "post"

For i As Integer = 0 To rf.Count - 1
If (rf.GetKey(i).L ength < 2 OrElse
rf.GetKey(i).Su bstring(0, 2) <> "__") Then
Dim control As New HiddenField()

control.ID = rf.GetKey(i)
control.Value = rf.Item(i)
Page.Form.Contr ols.Add(control )
End If
Next
ClientScript.Re gisterClientScr iptBlock(GetTyp e(String),
"postform", "<script
language=""java script"">window .document.forms['Form1'].action=""" +
FormsAuthentica tion.GetRedirec tUrl(User.Ident ity.Name, False) +
""";window.docu ment.forms['Form1'].submit();</script>")
End If
Else
Response.Cookie s("widsplusform key").Value = ""
Response.Cookie s("widsplusform key").Path = "/widsplus"

Response.Redire ct(FormsAuthent ication.GetRedi rectUrl(User.Id entity.Name,
False))
End If
End Sub
Protected Overrides Sub Render(ByVal writer As
System.Web.UI.H tmlTextWriter)
Page.ClientScri pt.RegisterForE ventValidation( Page.Form.ID)
For Each control As Control In Page.Controls
Page.ClientScri pt.RegisterForE ventValidation( control.ID)
Next
MyBase.Render(w riter)
End Sub
"Robert" wrote:
Hi Steven,

I agree that this is a better, cleaner approach. In my response, i tried
this however and am still receiving the error. So I'm unsure what I am doing
wrong or if there is a way to do this that will work.

Thx.
R-

"Steven Cheng[MSFT]" wrote:
Thanks for Phillip's inputs,

Hi Robert,

I think Phillip's description on this is reasonable. Based on the document
of the EnableEventVali dation setting:

=============
ASP.NET controls create client-side script to raise post-back events on the
server. Because a malicious user could use the postback script to send
arbitrary post events to server controls, ASP.NET 2.0 controls validate the
event data to ensure the event was raised by client-side code rendered by
the control.
=============

the ASP.NET 2.0 by default will check the postback datas so as to ensure
all the form elements(contro ls) are generated and rendered by the asp.net
page's control structure rather than manually injected by clientside
user(scripts... ). So in your scenario, you use Response.Write to manually
generate the page's content (output html form elements....) which is not
under the control of ASP.NET page control structure, so we'll get such
exception when post back....

As Phillip has suggested, if possible, we'd recommend that we redesign the
page so as to avoid such manual page rendering...

Thanks,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
--------------------
| Thread-Topic: Viewstate issues after move to 2.0 from 1.1
| thread-index: AcXwWoXmdxcbpXh TQrqsDjsXYR0hNw ==
| X-WBNR-Posting-Host: 64.253.156.46
| From: "=?Utf-8?B?UGhpbGxpcCB XaWxsaWFtcw==?= "
<Ph************ **@webswapp.com >
| References: <82************ *************** *******@microso ft.com>
<C3************ *************** *******@microso ft.com>
| Subject: RE: Viewstate issues after move to 2.0 from 1.1
| Date: Wed, 23 Nov 2005 10:20:03 -0800
| Lines: 165
| Message-ID: <C6************ *************** *******@microso ft.com>
| MIME-Version: 1.0
| Content-Type: text/plain;
| charset="Utf-8"
| Content-Transfer-Encoding: 8bit
| X-Newsreader: Microsoft CDO for Windows 2000
| Content-Class: urn:content-classes:message
| Importance: normal
| Priority: normal
| X-MimeOLE: Produced By Microsoft MimeOLE V6.00.3790.0
| Newsgroups: microsoft.publi c.dotnet.framew ork.aspnet
| NNTP-Posting-Host: TK2MSFTNGXA03.p hx.gbl 10.40.2.250
| Path: TK2MSFTNGXA02.p hx.gbl!TK2MSFTN GXA03.phx.gbl
| Xref: TK2MSFTNGXA02.p hx.gbl
microsoft.publi c.dotnet.framew ork.aspnet:3605 18
| X-Tomcat-NG: microsoft.publi c.dotnet.framew ork.aspnet
|
| Hi Robert,
|
| I think the problem you got is because your code simulated the steps
taken
| by a hacker who might want to violate the security of your site. ASP.NET
2.0
| attempts to ensure that all postback requests were triggered by code
rendered
| from the page’s server side controls (during the previous request). In
other
| words, ASP.NET validates View State to verify that it came from the
correct
| page, but your code in the method OutputFormData in formredirect.as px
wrote
| everything including the ("<!DOCTYPE>â ?from scratch.
|
| I would suggest that you turn on back again the enableeventvali dation and
| re-program the page named "formredirect.a spx" to use the page controls
| collection to add content within the form instead of the Response.Write
| method to write an html form to the browser.
|
| Let ASP.NET handles its ViewState to ensure the security of your site.
|
| --
| HTH,
| Phillip Williams
| http://www.societopia.net
| http://www.webswapp.com
|
|
| "Robert" wrote:
|
| > Some more info.
| >
| > I turned of "eventvalidatio n" (enableeventval idation=false in
web.config)
| > and that appears to prevent the errors although since they are sporadic
i
| > can't be 100% sure for a couple of days.
| >
| > So then my question becomes what exactly triggers "event validation" to
| > return an error? What exactly is it checking?
| >
| > I prefer not to disable security features so i'd prefer to fix my
| > redirection function so it doesn't trigger the error rather than
disable
| > event validation.
| >
| > "Robert" wrote:
| >
| > > I have an app that was originally 1.1, now migrated to 2.0 and have
run into
| > > some sporadic viewstate errors...usuall y saying the viewstate is
invalid,
| > > eventvalidation failed or mac error.
| > >
| > > My web config does specify a machinekey setting:
| > >
| > > <machineKey
| > >
validationKey=" 447C05E8B3A7140 1CC4CAE5513A7F1 A3494A3618EE819 316AAD1D58433F2 3
6A759D66FB41545 00E01EB4E1BC1DE 42046E2D652D391 CB8367A16494388 67A02EB"
| > > decryptionKey=" CE8D47C43312A14 4B49DE5E8D3D3CA 2CDEA230077AFB8 6CB"
| > > validation="SHA 1"/>
| > >
| > > The errors are occuring during some custom code that i wrote that
saves form
| > > data when a user's login times out and restores it by reposting it
after the
| > > user logs in.
| > >
| > > Specifically, in the global.asax file there is a function as below
| > > (truncated to shorten). When the user's session times out from
inactivity,
| > > the entire request.form object (all posted data) is saved in the
cache with a
| > > key saved as a cookie on the user's machine.
| > >
| > > Sub Application_Aut henticateReques t(ByVal sender As Object, ByVal e
As
| > > EventArgs)
| > > ' Fires upon attempting to authenticate the user
| > > If (Request.IsAuth enticated) Then
| > > ............... .........
| > > ElseIf (Request.Form.C ount > 0 AndAlso
| > > (Request.Cookie s("widsplusform key") Is Nothing OrElse
| > > Request.Cookies ("widsplusformk ey").Value = "") AndAlso
Request.Path.To Lower
| > > <> "/widsplus/login.aspx" AndAlso Request.Path.To Lower <>
"login.aspx ") Then
| > > Dim guidstring As String = Guid.NewGuid.To String
| > >
| > > ' Save any posted form data
| > > System.Web.Http Context.Current .Cache.Add(guid string,
| > > Request.Form, Nothing, Now.AddMinutes( 16), Cache.NoSliding Expiration,
| > > Caching.CacheIt emPriority.Norm al, Nothing)
| > > ' save cookie with guid string
| > > Response.Cookie s("widsplusform key").Value = guidstring
| > > Response.Cookie s("widsplusform key").Path = "/widsplus"
| > > Response.Cookie s("widsplusform key").Expires =
| > > Now().AddMinute s(15)
| > > End If
| > > End Sub
| > >
| > > Next, on the logon page, once the user is authenticated, it redirects
| > > manually to another page called "formredirect.a spx". The code on
that page
| > > (below) custom generates a page reconstructing the form data and then
posting
| > > it to the original page the user was on. This preserves the form
data so the
| > > user can continue from where they left off.
| > >
| > > This process worked 100% fine in ASP.NET 1.1. It is only once the
| > > application was migrated to 2.0 that the errors began. And they only
happen
| > > part of the time and almost seem related to the amount of form data
that
| > > needs to be reposted?
| > >
| > > Any ideas how to correct or why the errors only occur part of the
time etc.
| > > I will probably try turning off eventvalidation to see if that is the
reason
| > > since it is difference i can see in the data that is posted back.
| > >
| > >
| > > (Code for formredirect.as px - aspx file is blank and the below
generates all
| > > of the html).
| > >
| > > Public Sub OutputFormData( )
| > > Response.Write( "<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML
1.0
| > > Transitional//EN""
| > > ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d"">" +
Chr(10))
| > > Response.Write( "<html lang=""en"">" + Chr(10))
| > > Response.Write( " <head>" + Chr(10))
| > > Response.Write( " <title>See Spot Reload the
Form!!!</title>" +
| > > Chr(10))
| > > Response.Write( " </head>" + Chr(10))
| > > Response.Write( " <body bgcolor=""#ffff ff"">" + Chr(10))
| > > Response.Write( " <div id=""showprogre ss""
style=""DISPLAY :
| > > inline; VISIBILITY: visible; WIDTH: 100%; POSITION: absolute"">" +
Chr(10))
| > > Response.Write( " <p align=""center" "><img
| > > src=""globalima ges/transp.gif"" width=""5"" height=""50"">< br>" +
Chr(10))
| > > Response.Write( " <font face=""verdana" " size=""4""
| > > color=""#ffcc66 ""><b>Resubmitt ing Original Request...Pleas e
| > > Wait...</b></font><br><br>" + Chr(10))
| > > Response.Write( " <img
| > > src=""globalima ges/progressbarslow er.gif""><br>" + Chr(10))
| > > Response.Write( " <font face=""verdana" "
color=""#dddddd ""
| > > size=""1"">This may take a few moments...</font><br><br>" + Chr(10))
| > > Response.Write( " <a href=""mainmenu .aspx""><font
| > > face=""verdana" " size=""2"" color=""#ffcc66 ""><b>Cance l & Return to
Main
| > > Menu</b></font></a></p></div>" + Chr(10))
| > >
| > > If (Not (Request.Cookie s("widsplusform key") Is Nothing)
AndAlso
| > > Request.Cookies ("widsplusformk ey").Value <> "" AndAlso Not
| > >
(System.Web.Htt pContext.Curren t.Cache(Request .Cookies("widsp lusformkey").Va l
ue) Is Nothing)) Then
| > > Dim rf As Specialized.Nam eValueCollectio n =
| > >
CType(System.We b.HttpContext.C urrent.Cache(Re quest.Cookies(" widsplusformkey "
).Value), Specialized.Nam eValueCollectio n)
| > >
| > > Response.Flush( )
| > > If Not (rf Is Nothing) Then
| > > Response.Write( "<form name=""Form1""
method=""post""
| > > action=""" + FormsAuthentica tion.GetRedirec tUrl(User.Ident ity.Name,
False) +
| > > """ id=""Form1"">" + Chr(10))
| > > For i As Integer = 0 To rf.Count - 1
| > > Response.Write( "<input type=""hidden""
name=""" +
| > > rf.GetKey(i) + """ id=""" + rf.GetKey(i) + """ value=""" + rf.Item(i)
+ """>"
| > > + Chr(10))
| > > Next
| > > Response.Write( "</form>" + Chr(10) + "<script
| > > language=javasc ript>" + Chr(10) +
"window.documen t.forms['Form1'].submit()" +
| > > Chr(10) + "</script>" + Chr(10))
| > > Response.Write( " </body>")
| > > Response.Write( "</html>")
| > > ' clear the saved post data
| > >
| > >
System.Web.Http Context.Current .Cache.Remove(R equest.Cookies( "widsplusformke y
").Value)
| > > Response.Cookie s("widsplusform key").Value = ""
| > > Response.Cookie s("widsplusform key").Path =
"/widsplus"
| > > End If
| > > Else
| > > Response.Write( " </body>")
| > > Response.Write( "</html>")
| > > Response.Cookie s("widsplusform key").Value = ""
| > > Response.Cookie s("widsplusform key").Path = "/widsplus"
| > >
| > >
Response.Redire ct(FormsAuthent ication.GetRedi rectUrl(User.Id entity.Name,
| > > False))
| > > End If
| > > End Sub
|

Nov 24 '05 #7
Hi Robert,

If I understood your code correctly: you persist the entire form in the
cache and want to repopulate its controls after you login. You could
retrieve the HTMLForm object using the Page.FindContro ls and then reconstruct
it using all of the rich features available in the Page.Controls collection,
as I did in this example: http://www.societopia.net/samples/page_form1.aspx

Basically I put a form on one page then persisted in the cache and retrieved
all of its controls in the redirected to page without any troubles with the
ViewState.

--
HTH,
Phillip Williams
http://www.societopia.net
http://www.webswapp.com
"Robert" wrote:
Hi Philip,

Your suggestion was an interesting one and so i implemented it (code is
below). However, I still receive the same viewstate error. I tried having
the page not output viewstate itself. I tried having it output viewstate on
its own. It tried suppressing the original viewstate and i tried not
suppressing it.

In all cases I still get the error. Any other ideas/suggestions re the code
below?

What I'm suspecting is that either of the two below is ultimately
responsible for the error:

1) Because the type of the form controls i generate doesn't match the
original type (obviously i can't tell what the original type was...)
2) and/or the url of the page is being used to validate (the url
formredirection .aspx is not the same as the original).

Because this is in intranet site and didn't originally under 1.1 have event
validation I can probably just set this to false in the web config.

But i agree that ideally I would want to leave it on which is why i'm
spending considerable time trying to figure out a way around this.

Thx.
R-

Code for "formredirectio n.aspx":

<%@ Page Language="vb" EnableViewState ="false" EnableEventVali dation="false"
ValidateRequest =false AutoEventWireup ="false"
Inherits="WIDSP LUS.NET.formred irection2" CodeFile="formr edirection2.asp x.vb"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>See Spot Reload the Form!!!</title>
</head>
<body bgcolor="#fffff f">
<form runat="server">
</form>
</body>
</html>

Code behind:

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArg s) Handles MyBase.Load
'Put user code to initialize the page here
If (Not (Request.Cookie s("widsplusform key") Is Nothing) AndAlso
Request.Cookies ("widsplusformk ey").Value <> "" AndAlso Not
(System.Web.Htt pContext.Curren t.Cache(Request .Cookies("widsp lusformkey").Va lue) Is Nothing)) Then
Dim rf As Specialized.Nam eValueCollectio n =
CType(System.We b.HttpContext.C urrent.Cache(Re quest.Cookies(" widsplusformkey ").Value), Specialized.Nam eValueCollectio n)

If Not (rf Is Nothing) Then
' Clear the saved post data

System.Web.Http Context.Current .Cache.Remove(R equest.Cookies( "widsplusformke y").Value)
' Clear cookies
Response.Cookie s("widsplusform key").Value = ""
Response.Cookie s("widsplusform key").Path = "/widsplus"
' Output progress indicator
Response.Write( "<div id=""showprogre ss""
style=""DISPLAY : inline; VISIBILITY: visible; WIDTH: 100%; POSITION:
absolute"">" + Chr(10))
Response.Write( " <p align=""center" "><img
src=""globalima ges/transp.gif"" width=""5"" height=""50"">< br>" + Chr(10))
Response.Write( " <font face=""verdana" " size=""4""
color=""#ffcc66 ""><b>Resubmitt ing Original Request...Pleas e
Wait...</b></font><br><br>" + Chr(10))
Response.Write( " <img
src=""globalima ges/progressbarslow er.gif""><br>" + Chr(10))
Response.Write( " <font face=""verdana" "
color=""#dddddd "" size=""1"">This may take a few moments...</font><br><br>" +
Chr(10))
Response.Write( " <a href=""mainmenu .aspx""><font
face=""verdana" " size=""2"" color=""#ffcc66 ""><b>Cance l & Return to Main
Menu</b></font></a></p></div>" + Chr(10))
Response.Flush( )

' Construct form dynamically
Page.Form.ID = "Form1"
Page.Form.Name = "Form1"
Page.Form.Metho d = "post"

For i As Integer = 0 To rf.Count - 1
If (rf.GetKey(i).L ength < 2 OrElse
rf.GetKey(i).Su bstring(0, 2) <> "__") Then
Dim control As New HtmlInputHidden ()

control.Name = rf.GetKey(i)
control.ID = rf.GetKey(i)
control.Value = rf.Item(i)

Page.Form.Contr ols.Add(control )
End If
Next
ClientScript.Re gisterClientScr iptBlock(GetTyp e(String),
"postform", "<script
language=""java script"">window .document.forms['Form1'].action=""" +
FormsAuthentica tion.GetRedirec tUrl(User.Ident ity.Name, False) +
""";window.docu ment.forms['Form1'].submit();</script>")
End If
Else
Response.Cookie s("widsplusform key").Value = ""
Response.Cookie s("widsplusform key").Path = "/widsplus"

Response.Redire ct(FormsAuthent ication.GetRedi rectUrl(User.Id entity.Name,
False))
End If
End Sub

"Phillip Williams" wrote:
Hi Robert,

I think the problem you got is because your code simulated the steps taken
by a hacker who might want to violate the security of your site. ASP.NET 2.0
attempts to ensure that all postback requests were triggered by code rendered
from the page’s server side controls (during the previous request). In other
words, ASP.NET validates View State to verify that it came from the correct
page, but your code in the method OutputFormData in formredirect.as px wrote
everything including the ("<!DOCTYPE> ” from scratch.

I would suggest that you turn on back again the enableeventvali dation and
re-program the page named "formredirect.a spx" to use the page controls
collection to add content within the form instead of the Response.Write
method to write an html form to the browser.

Let ASP.NET handles its ViewState to ensure the security of your site.

--
HTH,
Phillip Williams
http://www.societopia.net
http://www.webswapp.com
"Robert" wrote:
Some more info.

I turned of "eventvalidatio n" (enableeventval idation=false in web.config)
and that appears to prevent the errors although since they are sporadic i
can't be 100% sure for a couple of days.

So then my question becomes what exactly triggers "event validation" to
return an error? What exactly is it checking?

I prefer not to disable security features so i'd prefer to fix my
redirection function so it doesn't trigger the error rather than disable
event validation.

"Robert" wrote:

> I have an app that was originally 1.1, now migrated to 2.0 and have run into
> some sporadic viewstate errors...usuall y saying the viewstate is invalid,
> eventvalidation failed or mac error.
>
> My web config does specify a machinekey setting:
>
> <machineKey
> validationKey=" 447C05E8B3A7140 1CC4CAE5513A7F1 A3494A3618EE819 316AAD1D58433F2 36A759D66FB4154 500E01EB4E1BC1D E42046E2D652D39 1CB8367A1649438 867A02EB"
> decryptionKey=" CE8D47C43312A14 4B49DE5E8D3D3CA 2CDEA230077AFB8 6CB"
> validation="SHA 1"/>
>
> The errors are occuring during some custom code that i wrote that saves form
> data when a user's login times out and restores it by reposting it after the
> user logs in.
>
> Specifically, in the global.asax file there is a function as below
> (truncated to shorten). When the user's session times out from inactivity,
> the entire request.form object (all posted data) is saved in the cache with a
> key saved as a cookie on the user's machine.
>
> Sub Application_Aut henticateReques t(ByVal sender As Object, ByVal e As
> EventArgs)
> ' Fires upon attempting to authenticate the user
> If (Request.IsAuth enticated) Then
> ............... .........
> ElseIf (Request.Form.C ount > 0 AndAlso
> (Request.Cookie s("widsplusform key") Is Nothing OrElse
> Request.Cookies ("widsplusformk ey").Value = "") AndAlso Request.Path.To Lower
> <> "/widsplus/login.aspx" AndAlso Request.Path.To Lower <> "login.aspx ") Then
> Dim guidstring As String = Guid.NewGuid.To String
>
> ' Save any posted form data
> System.Web.Http Context.Current .Cache.Add(guid string,
> Request.Form, Nothing, Now.AddMinutes( 16), Cache.NoSliding Expiration,
> Caching.CacheIt emPriority.Norm al, Nothing)
> ' save cookie with guid string
> Response.Cookie s("widsplusform key").Value = guidstring
> Response.Cookie s("widsplusform key").Path = "/widsplus"
> Response.Cookie s("widsplusform key").Expires =
> Now().AddMinute s(15)
> End If
> End Sub
>
> Next, on the logon page, once the user is authenticated, it redirects
> manually to another page called "formredirect.a spx". The code on that page
> (below) custom generates a page reconstructing the form data and then posting
> it to the original page the user was on. This preserves the form data so the
> user can continue from where they left off.
>
> This process worked 100% fine in ASP.NET 1.1. It is only once the
> application was migrated to 2.0 that the errors began. And they only happen
> part of the time and almost seem related to the amount of form data that
> needs to be reposted?
>
> Any ideas how to correct or why the errors only occur part of the time etc.
> I will probably try turning off eventvalidation to see if that is the reason
> since it is difference i can see in the data that is posted back.
>
>
> (Code for formredirect.as px - aspx file is blank and the below generates all
> of the html).
>
> Public Sub OutputFormData( )
> Response.Write( "<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0
> Transitional//EN""
> ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d"">" + Chr(10))
> Response.Write( "<html lang=""en"">" + Chr(10))
> Response.Write( " <head>" + Chr(10))
> Response.Write( " <title>See Spot Reload the Form!!!</title>" +
> Chr(10))
> Response.Write( " </head>" + Chr(10))
> Response.Write( " <body bgcolor=""#ffff ff"">" + Chr(10))
> Response.Write( " <div id=""showprogre ss"" style=""DISPLAY :
> inline; VISIBILITY: visible; WIDTH: 100%; POSITION: absolute"">" + Chr(10))
> Response.Write( " <p align=""center" "><img
> src=""globalima ges/transp.gif"" width=""5"" height=""50"">< br>" + Chr(10))
> Response.Write( " <font face=""verdana" " size=""4""
> color=""#ffcc66 ""><b>Resubmitt ing Original Request...Pleas e
> Wait...</b></font><br><br>" + Chr(10))
> Response.Write( " <img
> src=""globalima ges/progressbarslow er.gif""><br>" + Chr(10))
> Response.Write( " <font face=""verdana" " color=""#dddddd ""
> size=""1"">This may take a few moments...</font><br><br>" + Chr(10))
> Response.Write( " <a href=""mainmenu .aspx""><font
> face=""verdana" " size=""2"" color=""#ffcc66 ""><b>Cance l & Return to Main
> Menu</b></font></a></p></div>" + Chr(10))
>
> If (Not (Request.Cookie s("widsplusform key") Is Nothing) AndAlso
> Request.Cookies ("widsplusformk ey").Value <> "" AndAlso Not
> (System.Web.Htt pContext.Curren t.Cache(Request .Cookies("widsp lusformkey").Va lue) Is Nothing)) Then
> Dim rf As Specialized.Nam eValueCollectio n =
> CType(System.We b.HttpContext.C urrent.Cache(Re quest.Cookies(" widsplusformkey ").Value), Specialized.Nam eValueCollectio n)
>
> Response.Flush( )
> If Not (rf Is Nothing) Then
> Response.Write( "<form name=""Form1"" method=""post""
> action=""" + FormsAuthentica tion.GetRedirec tUrl(User.Ident ity.Name, False) +
> """ id=""Form1"">" + Chr(10))
> For i As Integer = 0 To rf.Count - 1
> Response.Write( "<input type=""hidden"" name=""" +
> rf.GetKey(i) + """ id=""" + rf.GetKey(i) + """ value=""" + rf.Item(i) + """>"
> + Chr(10))
> Next
> Response.Write( "</form>" + Chr(10) + "<script
> language=javasc ript>" + Chr(10) + "window.documen t.forms['Form1'].submit()" +
> Chr(10) + "</script>" + Chr(10))
> Response.Write( " </body>")
> Response.Write( "</html>")
> ' clear the saved post data
>
> System.Web.Http Context.Current .Cache.Remove(R equest.Cookies( "widsplusformke y").Value)
> Response.Cookie s("widsplusform key").Value = ""
> Response.Cookie s("widsplusform key").Path = "/widsplus"
> End If
> Else
> Response.Write( " </body>")
> Response.Write( "</html>")
> Response.Cookie s("widsplusform key").Value = ""
> Response.Cookie s("widsplusform key").Path = "/widsplus"
>
> Response.Redire ct(FormsAuthent ication.GetRedi rectUrl(User.Id entity.Name,
> False))
> End If
> End Sub

Nov 24 '05 #8
Hey Robert,

Thanks for your quick response.
From your further description and the code snippet you provided, seems
you're still using the Response.Write .... means to output page content(
this is usually what the old ASP or other scripting based dynamic document
use...). Is it possible that we change to utilize the ASP.NET server
control model , using Response.Write is really not a good idea. I'd rather
recommend you just clear up the ASPX's content and using the following code
block inline (as classic ASP do)

<%@page .....%>

<%

//all code here

%>
Also, as for your problem on
=============== ====
The moment I use the code at the end of the below where the script changes
the form action for postback to the original page (prior to the user having
timed-out), then i end up with the viewstate error.
=============== ====

if you're using the new ASP.NET control model, you 'll find that ASP.NET
2.0 provide "CrossPage Posting" functionality which help us to easily post
from one aspx page to another (we don't need to manually change the html
form's action attribute...), what we need to do is changing the Button
Control's PostBackUrl property , like:

protected void RadioButton_Che ckedChanged(obj ect sender, EventArgs e)
{
RadioButton rb = (RadioButton)se nder;

if (rb == RadioButton1)
{
btnPostBack.Pos tBackUrl = "~/AccessTestPage. aspx";
}
else
{
btnPostBack.Pos tBackUrl = "~/FtpWebPage.aspx ";
}
}
#Cross-Page Posting in ASP.NET Web Pages
http://msdn2.microsoft.com/en-us/library/ms178139.aspx
In addition, as for storing form's post data for later use, I think this is
done by default for ASP.NET page (if viewstate enabled), most of each
server control's properties will be persisted in ViewState for sequential
postback use... However, when there occurs timeout, of course, this is an
exceptional scenario, we need to write our own code to handel it (e.g store
them in cache or any other storage and reset them to asp.net page's
controls properties later....). Again this require that we utilize the
ASP.NET page control model ....

Thanks,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)


--------------------
| Thread-Topic: Viewstate issues after move to 2.0 from 1.1
| thread-index: AcXwwFvzbT+awft 0ROCI4qVIXc4SAA ==
| X-WBNR-Posting-Host: 67.180.214.235
| From: =?Utf-8?B?Um9iZXJ0?= <ro*****@noemai l.nospam>
| References: <82************ *************** *******@microso ft.com>
<C3************ *************** *******@microso ft.com>
<C6************ *************** *******@microso ft.com>
<$1************ *@TK2MSFTNGXA02 .phx.gbl>
<E3************ *************** *******@microso ft.com>
| Subject: RE: Viewstate issues after move to 2.0 from 1.1
| Date: Wed, 23 Nov 2005 22:29:01 -0800
| Lines: 437
| Message-ID: <84************ *************** *******@microso ft.com>
| MIME-Version: 1.0
| Content-Type: text/plain;
| charset="Utf-8"
| Content-Transfer-Encoding: 8bit
| X-Newsreader: Microsoft CDO for Windows 2000
| Content-Class: urn:content-classes:message
| Importance: normal
| Priority: normal
| X-MimeOLE: Produced By Microsoft MimeOLE V6.00.3790.0
| Newsgroups: microsoft.publi c.dotnet.framew ork.aspnet
| NNTP-Posting-Host: TK2MSFTNGXA03.p hx.gbl 10.40.2.250
| Path: TK2MSFTNGXA02.p hx.gbl!TK2MSFTN GP08.phx.gbl!TK 2MSFTNGXA03.phx .gbl
| Xref: TK2MSFTNGXA02.p hx.gbl
microsoft.publi c.dotnet.framew ork.aspnet:3606 36
| X-Tomcat-NG: microsoft.publi c.dotnet.framew ork.aspnet
|
| Steven,
|
| Below is the most recent revision i tried of the ASPX and codebehind for
the
| formredirection page.
|
| What I've found is that if instead of having the clientside script i
output
| to the page change the form action value to the final page and let the
page
| post back to itself, then no error is returned. However, of course, this
| defeats the purpose.
|
| The moment I use the code at the end of the below where the script
changes
| the form action for postback to the original page (prior to the user
having
| timed-out), then i end up with the viewstate error.
|
| I am unable to determine any way to get this to work with eventvalidation
| turned on. This may well be by design.
|
| I tried finding a way to dynamically turn of eventvalidation under the
| theory that i could perhaps have the final destination page disable it's
| eventvalidation temporarily but no property exists for this.
|
| All combinations and modifications I've made have been unable to prevent
the
| error.
|
| So I'm still left with having to just turn off eventvalidation
application
| wide in order to make this functionality work.
|
| I'm a bit surprised that MS didn't look at adding this type of
functionality
| into ASP.NET...i.e. ability to save form data when a timeout occurs for
login
| and then restore it afterwards. This makes an application much more
| user-friendly if you have forms that contain a fair number of fields
since if
| the user gets interrupted and then goes back, the data is preserved on
the
| server and restored by the code I wrote after the user re-logs in as
opposed
| to the common and standard behavior that they do get back to the same
page
| afterwards but with everything completely blank - all their data lost.
|
| If anyone has suggestions on what speciifically I could change in the
below
| that would make it work, I'd be very grateful. But I'm getting the
| impression this is a lost cause (perhaps by design).
|
| Thx.
| R-
|
| Current Code Version:
|
| <%@ Page Language="vb" EnableViewState ="true"
EnableEventVali dation="true"
| ValidateRequest =false AutoEventWireup ="false"
| Inherits="WIDSP LUS.NET.formred irection2"
CodeFile="formr edirection2.asp x.vb"
| %>
| <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
| "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">
| <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
| <head>
| <title>See Spot Reload the Form!!!</title>
| </head>
| <body bgcolor="#fffff f">
| <form runat="server">
| </form>
| </body>
| </html>
|
|
|
| Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
| System.EventArg s) Handles MyBase.Load
| 'Put user code to initialize the page here
| If (Page.IsPostBac k) Then
| Exit Sub ' Should not ever happen
| End If
| If (Not (Request.Cookie s("widsplusform key") Is Nothing)
AndAlso
| Request.Cookies ("widsplusformk ey").Value <> "" AndAlso Not
|
(System.Web.Htt pContext.Curren t.Cache(Request .Cookies("widsp lusformkey").Va l
ue) Is Nothing)) Then
| Dim rf As Specialized.Nam eValueCollectio n =
|
CType(System.We b.HttpContext.C urrent.Cache(Re quest.Cookies(" widsplusformkey "
).Value), Specialized.Nam eValueCollectio n)
|
| If Not (rf Is Nothing) Then
| ' Clear the saved post data
|
|
System.Web.Http Context.Current .Cache.Remove(R equest.Cookies( "widsplusformke y
").Value)
| ' Clear cookies
| Response.Cookie s("widsplusform key").Value = ""
| Response.Cookie s("widsplusform key").Path = "/widsplus"
| ' Output progress indicator
| Response.Write( "<div id=""showprogre ss""
| style=""DISPLAY : inline; VISIBILITY: visible; WIDTH: 100%; POSITION:
| absolute"">" + Chr(10))
| Response.Write( " <p align=""center" "><img
| src=""globalima ges/transp.gif"" width=""5"" height=""50"">< br>" + Chr(10))
| Response.Write( " <font face=""verdana" " size=""4""
| color=""#ffcc66 ""><b>Resubmitt ing Original Request...Pleas e
| Wait...</b></font><br><br>" + Chr(10))
| Response.Write( " <img
| src=""globalima ges/progressbarslow er.gif""><br>" + Chr(10))
| Response.Write( " <font face=""verdana" "
| color=""#dddddd "" size=""1"">This may take a few
moments...</font><br><br>" +
| Chr(10))
| Response.Write( " <a href=""mainmenu .aspx""><font
| face=""verdana" " size=""2"" color=""#ffcc66 ""><b>Cance l & Return to Main
| Menu</b></font></a></p></div>" + Chr(10))
| Response.Flush( )
|
| ' Construct form dynamically
| Page.Form.ID = "Form1"
| Page.Form.Name = "Form1"
| Page.Form.Metho d = "post"
|
| For i As Integer = 0 To rf.Count - 1
| If (rf.GetKey(i).L ength < 2 OrElse
| rf.GetKey(i).Su bstring(0, 2) <> "__") Then
| Dim control As New HiddenField()
|
| control.ID = rf.GetKey(i)
| control.Value = rf.Item(i)
| Page.Form.Contr ols.Add(control )
| End If
| Next
|
ClientScript.Re gisterClientScr iptBlock(GetTyp e(String),
| "postform", "<script
| language=""java script"">window .document.forms['Form1'].action=""" +
| FormsAuthentica tion.GetRedirec tUrl(User.Ident ity.Name, False) +
| """;window.docu ment.forms['Form1'].submit();</script>")
| End If
| Else
| Response.Cookie s("widsplusform key").Value = ""
| Response.Cookie s("widsplusform key").Path = "/widsplus"
|
| Response.Redire ct(FormsAuthent ication.GetRedi rectUrl(User.Id entity.Name,
| False))
| End If
| End Sub
|
|
| Protected Overrides Sub Render(ByVal writer As
| System.Web.UI.H tmlTextWriter)
| Page.ClientScri pt.RegisterForE ventValidation( Page.Form.ID)
| For Each control As Control In Page.Controls
| Page.ClientScri pt.RegisterForE ventValidation( control.ID)
| Next
| MyBase.Render(w riter)
| End Sub
|
|
| "Robert" wrote:
|
| > Hi Steven,
| >
| > I agree that this is a better, cleaner approach. In my response, i
tried
| > this however and am still receiving the error. So I'm unsure what I am
doing
| > wrong or if there is a way to do this that will work.
| >
| > Thx.
| > R-
| >
| > "Steven Cheng[MSFT]" wrote:
| >
| > > Thanks for Phillip's inputs,
| > >
| > > Hi Robert,
| > >
| > > I think Phillip's description on this is reasonable. Based on the
document
| > > of the EnableEventVali dation setting:
| > >
| > > =============
| > > ASP.NET controls create client-side script to raise post-back events
on the
| > > server. Because a malicious user could use the postback script to
send
| > > arbitrary post events to server controls, ASP.NET 2.0 controls
validate the
| > > event data to ensure the event was raised by client-side code
rendered by
| > > the control.
| > > =============
| > >
| > > the ASP.NET 2.0 by default will check the postback datas so as to
ensure
| > > all the form elements(contro ls) are generated and rendered by the
asp.net
| > > page's control structure rather than manually injected by clientside
| > > user(scripts... ). So in your scenario, you use Response.Write to
manually
| > > generate the page's content (output html form elements....) which is
not
| > > under the control of ASP.NET page control structure, so we'll get
such
| > > exception when post back....
| > >
| > > As Phillip has suggested, if possible, we'd recommend that we
redesign the
| > > page so as to avoid such manual page rendering...
| > >
| > > Thanks,
| > >
| > > Steven Cheng
| > > Microsoft Online Support
| > >
| > > Get Secure! www.microsoft.com/security
| > > (This posting is provided "AS IS", with no warranties, and confers no
| > > rights.)
| > >
| > >
| > > --------------------
| > > | Thread-Topic: Viewstate issues after move to 2.0 from 1.1
| > > | thread-index: AcXwWoXmdxcbpXh TQrqsDjsXYR0hNw ==
| > > | X-WBNR-Posting-Host: 64.253.156.46
| > > | From: "=?Utf-8?B?UGhpbGxpcCB XaWxsaWFtcw==?= "
| > > <Ph************ **@webswapp.com >
| > > | References: <82************ *************** *******@microso ft.com>
| > > <C3************ *************** *******@microso ft.com>
| > > | Subject: RE: Viewstate issues after move to 2.0 from 1.1
| > > | Date: Wed, 23 Nov 2005 10:20:03 -0800
| > > | Lines: 165
| > > | Message-ID: <C6************ *************** *******@microso ft.com>
| > > | MIME-Version: 1.0
| > > | Content-Type: text/plain;
| > > | charset="Utf-8"
| > > | Content-Transfer-Encoding: 8bit
| > > | X-Newsreader: Microsoft CDO for Windows 2000
| > > | Content-Class: urn:content-classes:message
| > > | Importance: normal
| > > | Priority: normal
| > > | X-MimeOLE: Produced By Microsoft MimeOLE V6.00.3790.0
| > > | Newsgroups: microsoft.publi c.dotnet.framew ork.aspnet
| > > | NNTP-Posting-Host: TK2MSFTNGXA03.p hx.gbl 10.40.2.250
| > > | Path: TK2MSFTNGXA02.p hx.gbl!TK2MSFTN GXA03.phx.gbl
| > > | Xref: TK2MSFTNGXA02.p hx.gbl
| > > microsoft.publi c.dotnet.framew ork.aspnet:3605 18
| > > | X-Tomcat-NG: microsoft.publi c.dotnet.framew ork.aspnet
| > > |
| > > | Hi Robert,
| > > |
| > > | I think the problem you got is because your code simulated the
steps
| > > taken
| > > | by a hacker who might want to violate the security of your site.
ASP.NET
| > > 2.0
| > > | attempts to ensure that all postback requests were triggered by
code
| > > rendered
| > > | from the page’s server side controls (during the previous
request). In
| > > other
| > > | words, ASP.NET validates View State to verify that it came from the
| > > correct
| > > | page, but your code in the method OutputFormData in
formredirect.as px
| > > wrote
| > > | everything including the ("<!DOCTYPE>â ?from scratch.
| > > |
| > > | I would suggest that you turn on back again the
enableeventvali dation and
| > > | re-program the page named "formredirect.a spx" to use the page
controls
| > > | collection to add content within the form instead of the
Response.Write
| > > | method to write an html form to the browser.
| > > |
| > > | Let ASP.NET handles its ViewState to ensure the security of your
site.
| > > |
| > > | --
| > > | HTH,
| > > | Phillip Williams
| > > | http://www.societopia.net
| > > | http://www.webswapp.com
| > > |
| > > |
| > > | "Robert" wrote:
| > > |
| > > | > Some more info.
| > > | >
| > > | > I turned of "eventvalidatio n" (enableeventval idation=false in
| > > web.config)
| > > | > and that appears to prevent the errors although since they are
sporadic
| > > i
| > > | > can't be 100% sure for a couple of days.
| > > | >
| > > | > So then my question becomes what exactly triggers "event
validation" to
| > > | > return an error? What exactly is it checking?
| > > | >
| > > | > I prefer not to disable security features so i'd prefer to fix my
| > > | > redirection function so it doesn't trigger the error rather than
| > > disable
| > > | > event validation.
| > > | >
| > > | > "Robert" wrote:
| > > | >
| > > | > > I have an app that was originally 1.1, now migrated to 2.0 and
have
| > > run into
| > > | > > some sporadic viewstate errors...usuall y saying the viewstate
is
| > > invalid,
| > > | > > eventvalidation failed or mac error.
| > > | > >
| > > | > > My web config does specify a machinekey setting:
| > > | > >
| > > | > > <machineKey
| > > | > >
| > >
validationKey=" 447C05E8B3A7140 1CC4CAE5513A7F1 A3494A3618EE819 316AAD1D58433F2 3
| > > 6A759D66FB41545 00E01EB4E1BC1DE 42046E2D652D391 CB8367A16494388 67A02EB"
| > > | > >
decryptionKey=" CE8D47C43312A14 4B49DE5E8D3D3CA 2CDEA230077AFB8 6CB"
| > > | > > validation="SHA 1"/>
| > > | > >
| > > | > > The errors are occuring during some custom code that i wrote
that
| > > saves form
| > > | > > data when a user's login times out and restores it by reposting
it
| > > after the
| > > | > > user logs in.
| > > | > >
| > > | > > Specifically, in the global.asax file there is a function as
below
| > > | > > (truncated to shorten). When the user's session times out from
| > > inactivity,
| > > | > > the entire request.form object (all posted data) is saved in
the
| > > cache with a
| > > | > > key saved as a cookie on the user's machine.
| > > | > >
| > > | > > Sub Application_Aut henticateReques t(ByVal sender As Object,
ByVal e
| > > As
| > > | > > EventArgs)
| > > | > > ' Fires upon attempting to authenticate the user
| > > | > > If (Request.IsAuth enticated) Then
| > > | > > ............... .........
| > > | > > ElseIf (Request.Form.C ount > 0 AndAlso
| > > | > > (Request.Cookie s("widsplusform key") Is Nothing OrElse
| > > | > > Request.Cookies ("widsplusformk ey").Value = "") AndAlso
| > > Request.Path.To Lower
| > > | > > <> "/widsplus/login.aspx" AndAlso Request.Path.To Lower <>
| > > "login.aspx ") Then
| > > | > > Dim guidstring As String = Guid.NewGuid.To String
| > > | > >
| > > | > > ' Save any posted form data
| > > | > >
System.Web.Http Context.Current .Cache.Add(guid string,
| > > | > > Request.Form, Nothing, Now.AddMinutes( 16),
Cache.NoSliding Expiration,
| > > | > > Caching.CacheIt emPriority.Norm al, Nothing)
| > > | > > ' save cookie with guid string
| > > | > > Response.Cookie s("widsplusform key").Value =
guidstring
| > > | > > Response.Cookie s("widsplusform key").Path =
"/widsplus"
| > > | > > Response.Cookie s("widsplusform key").Expires =
| > > | > > Now().AddMinute s(15)
| > > | > > End If
| > > | > > End Sub
| > > | > >
| > > | > > Next, on the logon page, once the user is authenticated, it
redirects
| > > | > > manually to another page called "formredirect.a spx". The code
on
| > > that page
| > > | > > (below) custom generates a page reconstructing the form data
and then
| > > posting
| > > | > > it to the original page the user was on. This preserves the
form
| > > data so the
| > > | > > user can continue from where they left off.
| > > | > >
| > > | > > This process worked 100% fine in ASP.NET 1.1. It is only once
the
| > > | > > application was migrated to 2.0 that the errors began. And
they only
| > > happen
| > > | > > part of the time and almost seem related to the amount of form
data
| > > that
| > > | > > needs to be reposted?
| > > | > >
| > > | > > Any ideas how to correct or why the errors only occur part of
the
| > > time etc.
| > > | > > I will probably try turning off eventvalidation to see if that
is the
| > > reason
| > > | > > since it is difference i can see in the data that is posted
back.
| > > | > >
| > > | > >
| > > | > > (Code for formredirect.as px - aspx file is blank and the below
| > > generates all
| > > | > > of the html).
| > > | > >
| > > | > > Public Sub OutputFormData( )
| > > | > > Response.Write( "<!DOCTYPE html PUBLIC ""-//W3C//DTD
XHTML
| > > 1.0
| > > | > > Transitional//EN""
| > > | > > ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d"">" +
| > > Chr(10))
| > > | > > Response.Write( "<html lang=""en"">" + Chr(10))
| > > | > > Response.Write( " <head>" + Chr(10))
| > > | > > Response.Write( " <title>See Spot Reload the
| > > Form!!!</title>" +
| > > | > > Chr(10))
| > > | > > Response.Write( " </head>" + Chr(10))
| > > | > > Response.Write( " <body bgcolor=""#ffff ff"">" +
Chr(10))
| > > | > > Response.Write( " <div id=""showprogre ss""
| > > style=""DISPLAY :
| > > | > > inline; VISIBILITY: visible; WIDTH: 100%; POSITION:
absolute"">" +
| > > Chr(10))
| > > | > > Response.Write( " <p align=""center" "><img
| > > | > > src=""globalima ges/transp.gif"" width=""5"" height=""50"">< br>"
+
| > > Chr(10))
| > > | > > Response.Write( " <font face=""verdana" "
size=""4""
| > > | > > color=""#ffcc66 ""><b>Resubmitt ing Original Request...Pleas e
| > > | > > Wait...</b></font><br><br>" + Chr(10))
| > > | > > Response.Write( " <img
| > > | > > src=""globalima ges/progressbarslow er.gif""><br>" + Chr(10))
| > > | > > Response.Write( " <font face=""verdana" "
| > > color=""#dddddd ""
| > > | > > size=""1"">This may take a few moments...</font><br><br>" +
Chr(10))
| > > | > > Response.Write( " <a href=""mainmenu .aspx""><font
| > > | > > face=""verdana" " size=""2"" color=""#ffcc66 ""><b>Cance l &
Return to
| > > Main
| > > | > > Menu</b></font></a></p></div>" + Chr(10))
| > > | > >
| > > | > > If (Not (Request.Cookie s("widsplusform key") Is
Nothing)
| > > AndAlso
| > > | > > Request.Cookies ("widsplusformk ey").Value <> "" AndAlso Not
| > > | > >
| > >
(System.Web.Htt pContext.Curren t.Cache(Request .Cookies("widsp lusformkey").Va l
| > > ue) Is Nothing)) Then
| > > | > > Dim rf As Specialized.Nam eValueCollectio n =
| > > | > >
| > >
CType(System.We b.HttpContext.C urrent.Cache(Re quest.Cookies(" widsplusformkey "
| > > ).Value), Specialized.Nam eValueCollectio n)
| > > | > >
| > > | > > Response.Flush( )
| > > | > > If Not (rf Is Nothing) Then
| > > | > > Response.Write( "<form name=""Form1""
| > > method=""post""
| > > | > > action=""" +
FormsAuthentica tion.GetRedirec tUrl(User.Ident ity.Name,
| > > False) +
| > > | > > """ id=""Form1"">" + Chr(10))
| > > | > > For i As Integer = 0 To rf.Count - 1
| > > | > > Response.Write( "<input type=""hidden""
| > > name=""" +
| > > | > > rf.GetKey(i) + """ id=""" + rf.GetKey(i) + """ value=""" +
rf.Item(i)
| > > + """>"
| > > | > > + Chr(10))
| > > | > > Next
| > > | > > Response.Write( "</form>" + Chr(10) +
"<script
| > > | > > language=javasc ript>" + Chr(10) +
| > > "window.documen t.forms['Form1'].submit()" +
| > > | > > Chr(10) + "</script>" + Chr(10))
| > > | > > Response.Write( " </body>")
| > > | > > Response.Write( "</html>")
| > > | > > ' clear the saved post data
| > > | > >
| > > | > >
| > >
System.Web.Http Context.Current .Cache.Remove(R equest.Cookies( "widsplusformke y
| > > ").Value)
| > > | > > Response.Cookie s("widsplusform key").Value =
""
| > > | > > Response.Cookie s("widsplusform key").Path =
| > > "/widsplus"
| > > | > > End If
| > > | > > Else
| > > | > > Response.Write( " </body>")
| > > | > > Response.Write( "</html>")
| > > | > > Response.Cookie s("widsplusform key").Value = ""
| > > | > > Response.Cookie s("widsplusform key").Path =
"/widsplus"
| > > | > >
| > > | > >
| > >
Response.Redire ct(FormsAuthent ication.GetRedi rectUrl(User.Id entity.Name,
| > > | > > False))
| > > | > > End If
| > > | > > End Sub
| > > |
| > >
| > >
|

Nov 24 '05 #9
Hi Steven,

Thanks for your reply. The only remaining response.write statements were to
write out a div with a "progress bar" type message since the page we post to
might be a search page or other long-running page. I don't see how that
would cause an issue. However, I've changed it to also dynamically use a
literal control.

However, I still get the same error when the form posts itself to the
original page. I think you might not understand what I am trying to do.
Here is the sequence of actions from the user viewpoint.

1) They click an action button on a form they are on that we will call
dosomething.asp x.
2) Their session had timed out so ASP.NET redirects them to the login page.
In global.asax, I cache their entire Request.Form object to preserve any
information they had keyed that would otherwise now be lost.
3) The login page redirects them to formredirection .aspx when they login.
4) On formredirection .aspx, I construct a form with hidden form fields
holding the data that I had cached for the user - the data the user
originally posted to dosomething.asp x.
5) Form redirection changes its action tag and posts itself back to
dosomething.asp x
6) Dosomething.asp x sees the post request and takes that posted information
to populate its controls...i.e. viewstate and control state is restored back
to what it was in step 1. From the user point of view they have now gone
back with all their data intact.

The method I used in 1.1 required no modifications to the dosomething.asp x
page of which there are several hundred in the application.

Cross page posting does not work for this scenario because it stores the
form data of the original page in the "Previouspa ge" collection. It does not
restore the form data to the posted page and it is really just another method
of persisting information from one page to another.

Cross page posting would require me to add code to each of the pages of the
application (the dosomething.asp x) pages so that they would look at the
previouspage collection and use that data to rebuild their own control state
and form data values.

I've made several more modifications to my original code which is below.
The aspx page now has almost nothing on it other than a form tag. I prefer
not to use inline method for the page since everything else in the
application is code-behind and i prefer that model.

Thx.
R-
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArg s) Handles MyBase.Load
'Put user code to initialize the page here
If (Page.IsPostBac k) Then
Exit Sub ' Should not ever happen
End If
If (Not (Request.Cookie s("widsplusform key") Is Nothing) AndAlso
Request.Cookies ("widsplusformk ey").Value <> "" AndAlso Not
(System.Web.Htt pContext.Curren t.Cache(Request .Cookies("widsp lusformkey").Va lue) Is Nothing)) Then
Dim rf As Specialized.Nam eValueCollectio n =
CType(System.We b.HttpContext.C urrent.Cache(Re quest.Cookies(" widsplusformkey ").Value), Specialized.Nam eValueCollectio n)

If Not (rf Is Nothing) Then
' Clear the saved post data

System.Web.Http Context.Current .Cache.Remove(R equest.Cookies( "widsplusformke y").Value)
' Clear cookies
Response.Cookie s("widsplusform key").Value = ""
Response.Cookie s("widsplusform key").Path = "/widsplus"
' Output progress indicator
Dim hcontrol As New LiteralControl

hcontrol.ID = "showprogre ss"
hcontrol.Text = "<div style=""WIDTH: 100%; POSITION:
absolute; text-align: center; font-family: verdana""><img
src=""globalima ges/transp.gif"" width=""5"" height=""50"">< br><font
size=""4"" color=""#ffcc66 ""><b>Resubmitt ing Original Request...Pleas e
Wait...</b></font><br><br><i mg
src=""globalima ges/progressbarslow er.gif""><br><f ont color=""#dddddd ""
size=""1"">This may take a few moments...</font><br><br><a
href=""mainmenu .aspx""><font size=""2"" color=""#ffcc66 ""><b>Cance l & Return
to Main Menu</b></font></a></div>"
Page.Form.Contr ols.Add(hcontro l)

' Construct form dynamically
Page.Form.ID = "Form1"
Page.Form.Name = "Form1"
Page.Form.Metho d = "post"

For i As Integer = 0 To rf.Count - 1
If (rf.GetKey(i).L ength < 2 OrElse
rf.GetKey(i).Su bstring(0, 2) <> "__") Then
Dim control As New HiddenField()

control.ID = rf.GetKey(i)
control.Value = rf.Item(i)
Page.Form.Contr ols.Add(control )
End If
Next
ClientScript.Re gisterStartupSc ript(GetType(St ring),
"postform", "<script
language=""java script"">window .document.forms['Form1'].action=""" +
FormsAuthentica tion.GetRedirec tUrl(User.Ident ity.Name, False) + """;\\
window.document .forms['Form1'].submit();</script>")
End If
Else
Response.Cookie s("widsplusform key").Value = ""
Response.Cookie s("widsplusform key").Path = "/widsplus"

Response.Redire ct(FormsAuthent ication.GetRedi rectUrl(User.Id entity.Name,
False))
End If
End Sub

"Steven Cheng[MSFT]" wrote:
Hey Robert,

Thanks for your quick response.
From your further description and the code snippet you provided, seems
you're still using the Response.Write .... means to output page content(
this is usually what the old ASP or other scripting based dynamic document
use...). Is it possible that we change to utilize the ASP.NET server
control model , using Response.Write is really not a good idea. I'd rather
recommend you just clear up the ASPX's content and using the following code
block inline (as classic ASP do)

<%@page .....%>

<%

//all code here

%>
Also, as for your problem on
=============== ====
The moment I use the code at the end of the below where the script changes
the form action for postback to the original page (prior to the user having
timed-out), then i end up with the viewstate error.
=============== ====

if you're using the new ASP.NET control model, you 'll find that ASP.NET
2.0 provide "CrossPage Posting" functionality which help us to easily post
from one aspx page to another (we don't need to manually change the html
form's action attribute...), what we need to do is changing the Button
Control's PostBackUrl property , like:

protected void RadioButton_Che ckedChanged(obj ect sender, EventArgs e)
{
RadioButton rb = (RadioButton)se nder;

if (rb == RadioButton1)
{
btnPostBack.Pos tBackUrl = "~/AccessTestPage. aspx";
}
else
{
btnPostBack.Pos tBackUrl = "~/FtpWebPage.aspx ";
}
}
#Cross-Page Posting in ASP.NET Web Pages
http://msdn2.microsoft.com/en-us/library/ms178139.aspx
In addition, as for storing form's post data for later use, I think this is
done by default for ASP.NET page (if viewstate enabled), most of each
server control's properties will be persisted in ViewState for sequential
postback use... However, when there occurs timeout, of course, this is an
exceptional scenario, we need to write our own code to handel it (e.g store
them in cache or any other storage and reset them to asp.net page's
controls properties later....). Again this require that we utilize the
ASP.NET page control model ....

Thanks,

Steven Cheng
Microsoft Online Support


Nov 24 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2822
by: Ben Rush | last post by:
Hello World, Okay, I have spent the day browsing the newsgroups and reading up on article after article concerning ViewState corruption and so forth, and I have a couple questions. We intermittantly get the following exception - EXCEPTION MESSAGE: The viewstate is invalid for this page and might be corrupted. STACK TRACE:
2
1591
by: Chris Becker | last post by:
I am currently hosting my site with webhost4life.com and my visitors (well, just the visitors that are admins and try to do data entry, modification and removale) are constantly getting "Invalid Viewstate" errors. It seems that the problem could be that the asp.net worker process is constantly recycling. Anyone have any suggestions on how to solve this? Moving the viewstate to be stored in the session object didn't help since the...
3
3488
by: Gummy | last post by:
Hello, I have an ASPX page on which I place a UserControl 15 times (they only need to be static controls on the page). This UserControl is a set of two listboxes with radiobuttons above the listbox (to select between viewing a code or description in the listbox). There are also left and right arrows that move the selected items between the listboxes. In my Page_Load I assign each UserControl the appropriate DataTable and this...
6
6264
by: scottrm | last post by:
Hi Users seem to be getting the following intermitent error whe they post a form. Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKeyconfiguration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.
5
14071
by: russell.lane | last post by:
I'm getting the much-hated "validation of viewstate MAC failed" error. This is on an ASP.Net 2.0 app running in IIS with IE 6+ as the browser. The full error text is: Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machineKeyconfiguration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster. The app *is not* running in a cluster or...
5
7262
by: Mark Olbert | last post by:
Tonight's episode of me beating my head bloody against the monitor was the result of ViewState/ControlState information not being available when CreateChildControls() gets called for a CompositeControl. So, my question is, >>why<< isn't ViewState/ControlState available before CreateChildControls() gets called by the Framework? Is it just me, or does it seem really counterintuitive to be creating child controls on postback without the...
9
2671
by: =?Utf-8?B?TUNN?= | last post by:
I'm sure the answer to my question varies depending on the situation, but I am looking for a general "best practice". If I have an asp.net application and I load certain data from a database, should I use ViewState to store and reload the data, or should I load the data from the database on each postback? Assume for the sake of this question that I only care about performance, I don't care about ease of programming.
4
2289
by: =?Utf-8?B?TUNN?= | last post by:
I am trying to disable ViewState at the application level. I have the following line in my web.config: <pages enableViewState="false"></pages> But it is not working. What can I do?
0
9566
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9388
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9333
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9254
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8256
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6078
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4879
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2791
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2217
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.