c# asp.net asp.net-2.0 viewstate failed-to-load-viewstate

c# - La configuración de ViewStateUserKey me da un error de "Validación del MAC del estado de vista fallido"



asp.net asp.net-2.0 (5)

¿Se puede desactivar la codificación MAC de ViewState con el atributo EnableViewStateMac @Page?

Tengo lo siguiente en mi clase BasePage la que derivan todas mis páginas ASPX:

protected override void OnInit(EventArgs e) { base.OnInit(e); ViewStateUserKey = Session.SessionID; }

También tengo un machineKey configurado en Web.config . No creo que este error se deba a una granja de servidores web porque esto también ocurre en mi máquina dev.

Mi host ahora se ha actualizado a .NET 3.5 SP1. Después de esta actualización, cada vez que compilo con la configuración de ViewStateUserKey mencionada anteriormente, recibo constantemente el error "La validación de Viewstate MAC falló" en cada devolución de datos.

¿Qué estoy haciendo mal aquí? ¿Ya es necesario este ajuste con la última actualización del marco?


Está bien, llego un año tarde a la conversación, pero ¿cómo es esta la respuesta correcta? Esto se aplica solo en el caso de usuarios autenticados y el uso de ViewStateUserKey como nombre de usuario es mucho más fácil de adivinar que un ID de sesión GUID.

Por cierto, si desea "arreglar" el código en la parte superior, use el ID de sesión, sin embargo, debe configurar una variable de sesión para que el identificador de sesión deje de cambiar cada vez. Ex. Session["Anything"] = DateTime.Now

ViewStateUserKey = Session.SessionID;

Por supuesto, esto supone que va a utilizar sesiones, de lo contrario, necesitará alguna otra clave para usar, como el nombre de usuario o cualquier otro guid que se encuentre en una cookie.


He buscado un poco para encontrar la causa definitiva del problema. Esta publicación de Microsoft realmente ayudó a explicar todas las diferentes causas. http://support.microsoft.com/kb/2915218 causa 4 es lo que hemos encontrado y es un ViewStateUserKeyValue no válido

La configuración de ViewStateUserKey en Session.SessionID o User.Identity.Name no funcionó para nosotros.

Recibimos intermitentemente el error de validación debido a lo siguiente. Cuando IIS restablece el grupo de aplicaciones, la sesión se renueva en efecto causando el error. Abandonamos la sesión al iniciar sesión para evitar la reparación de la sesión, lo que también genera el error al iniciar sesión.

Lo que finalmente funcionó para nosotros fue una solución basada en cookies, que ahora se proporciona en VS2012.

public partial class SiteMaster : MasterPage { private const string AntiXsrfTokenKey = "__AntiXsrfToken"; private const string AntiXsrfUserNameKey = "__AntiXsrfUserName"; private string _antiXsrfTokenValue; protected void Page_Init(object sender, EventArgs e) { //First, check for the existence of the Anti-XSS cookie var requestCookie = Request.Cookies[AntiXsrfTokenKey]; Guid requestCookieGuidValue; //If the CSRF cookie is found, parse the token from the cookie. //Then, set the global page variable and view state user //key. The global variable will be used to validate that it matches in the view state form field in the Page.PreLoad //method. if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue)) { //Set the global token variable so the cookie value can be //validated against the value in the view state form field in //the Page.PreLoad method. _antiXsrfTokenValue = requestCookie.Value; //Set the view state user key, which will be validated by the //framework during each request Page.ViewStateUserKey = _antiXsrfTokenValue; } //If the CSRF cookie is not found, then this is a new session. else { //Generate a new Anti-XSRF token _antiXsrfTokenValue = Guid.NewGuid().ToString("N"); //Set the view state user key, which will be validated by the //framework during each request Page.ViewStateUserKey = _antiXsrfTokenValue; //Create the non-persistent CSRF cookie var responseCookie = new HttpCookie(AntiXsrfTokenKey) { //Set the HttpOnly property to prevent the cookie from //being accessed by client side script HttpOnly = true, //Add the Anti-XSRF token to the cookie value Value = _antiXsrfTokenValue }; //If we are using SSL, the cookie should be set to secure to //prevent it from being sent over HTTP connections if (FormsAuthentication.RequireSSL && Request.IsSecureConnection) responseCookie.Secure = true; //Add the CSRF cookie to the response Response.Cookies.Set(responseCookie); } Page.PreLoad += master_Page_PreLoad; } protected void master_Page_PreLoad(object sender, EventArgs e) { //During the initial page load, add the Anti-XSRF token and user //name to the ViewState if (!IsPostBack) { //Set Anti-XSRF token ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey; //If a user name is assigned, set the user name ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty; } //During all subsequent post backs to the page, the token value from //the cookie should be validated against the token in the view state //form field. Additionally user name should be compared to the //authenticated users name else { //Validate the Anti-XSRF token if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue || (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty)) { throw new InvalidOperationException("Validation of Anti-XSRF token failed."); } } } }

Source


Lo arreglé por ahora cambiando el código a:

protected override void OnInit(EventArgs e) { base.OnInit(e); if (User.Identity.IsAuthenticated) ViewStateUserKey = User.Identity.Name; }


MUY extraño, yo también tuve un problema similar durante 3 días y ahora lo resolví. 1. He habilitado la autenticación de formularios y tuve ssl falso

<forms defaultUrl="~/" loginUrl="~/Account/Login.aspx" requireSSL="false" timeout="2880" />

  1. pero en mi etiqueta httpcookies tuve requireSSL = true. Ya que en el Site.Master.cs usa cookies para configurar ViewStateUserKey, estaba teniendo problemas

  2. Por lo tanto, estaba recibiendo el error.

  3. Modifiqué esto a falso y reinicié la aplicación web, ahora todo está bien.