2010-08-31 84 views
1

所有形式在我的网站工作,除了这一次,当我提出这个形式我得到以下错误:奇怪的ASP.net错误

Server Error in '/********' Application. Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.

Source Error:

[No relevant source lines]

Source File: c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\alphapack\b9be7787\4e4ee265\App_Web_al4orjqe.6.cs Line: 0

Stack Trace:

[HttpException (0x80004005): Unable to validate data.]
System.Web.Configuration.MachineKeySection.GetDecodedData(Byte[] buf, Byte[] modifier, Int32 start, Int32 length, Int32& dataLength) +289 System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) +140

[ViewStateException: Invalid viewstate. Client IP: 10.10.0.103 Port: 2332 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8 (.NET CLR 3.5.30729) ViewState: /wEPDwUJNjMxODAxMzg2D2QWAmYPZBYGAgcPDxYEHghDc3NDbGFzcwUKbmF2QnV0dG9uTx4EXyFTQgICZGQCEQ8PFgIeBFRleHQFD0FkZCBOZXcgUHJvZHVjdGRkAhMPZBYCAgEPZBYEAgUPEGQPFhQCAQICAgMCBAIFAgYCBwIIAgkCCgILAgwCDQIOAg8CEAIRAhICEwIUFhQQBQRDYXJzBQE5ZxAFF8KgwqDCoMKgwqDCoMKgwqBGZXJyYXJpBQIxMWcQBSvCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoEJyb2tlbiBPbmVzBQIxOGcQBTnCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqBObyBXaGVlbHMFAjIyZxAFOsKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoE5vIFdpbmRvd3MFAjIzZxAFLcKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgRnVsbHkgV29ya2luZwUCMTlnEAUWwqDCoMKgwqDCoMKgwqDCoExhbWJvcwUCMTBnEAUmwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqBZZWxsb3cFAjE1ZxAFI8KgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgUmVkBQIxNmcQBSTCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoMKgwqDCoEJsdWUFAjE3ZxAFBkhvdXNlcwUCMTJnEAUYwqDCoMKgwqDCoMKgwqDCoE1hbnNp...]

[HttpException (0x80004005): Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.]
System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) +106
System.Web.UI.ViewStateException.ThrowMacValidationError(Exception inner, String persistedState) +14
System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) +242
System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) +4
System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState) +37 System.Web.UI.HiddenFieldPageStatePersister.Load() +207 System.Web.UI.Page.LoadPageStateFromPersistenceMedium() +105 System.Web.UI.Page.LoadAllState() +43 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +6785
System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +242
System.Web.UI.Page.ProcessRequest() +80 System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) +21
System.Web.UI.Page.ProcessRequest(HttpContext context) +49
ASP.admin_productcats_aspx.ProcessRequest(HttpContext context) in c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\alphapack\b9be7787\4e4ee265\App_Web_al4orjqe.6.cs:0 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75

代码是:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Data; 
using System.Data.SqlClient; 
using System.Configuration; 
using System.Collections; 

namespace ******** 
{ 
    public partial class productAdd : System.Web.UI.Page 
    { 
     // Navigation stuff 
     Category tree = null; 
     Dictionary<int, Category> dict = new Dictionary<int, Category>(); 
     ArrayList dicIndexes = new ArrayList(); 

     // Validate stock count 
     protected void validateStockCount(object source, ServerValidateEventArgs args) 
     { 
      try 
      { 
       int theCount = Convert.ToInt32(stockCount.Text); 
       if (theCount < 0) 
       { 
        args.IsValid = false; 
       } 
       else 
       { 
        args.IsValid = true ; 
       } 
      } 
      catch 
      { 
       args.IsValid = false ; 
      }    
     } 

     protected void Page_Load(object sender, EventArgs e) 
     { 

      limitedStock.Attributes.Add("onclick", "showHide()"); 

      // Action of the page 
      string pageAction = Request.QueryString["action"]; 

      using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString())) 
      { 
       cn.Open(); 

       // Posted a form to self 
       if (IsPostBack) 
       { 
        // Validate data 
        Page.Validate(); 
        if (Page.IsValid) 
        { 
         // New category 
         if (pageAction == "new") 
         { 
          // Get form vals 
          int selectedCatID = int.Parse(parent.SelectedItem.Value.ToString()); 
          string prodName = productName.Text; 
          bool isLim = limitedStock.Checked; 
          //int prodStockCount = int.Parse(stockCount.ToString()); 
          int prodStockCount = 3; 
          bool isForSale = !hidden.Checked; 

          using (SqlCommand cmd = new SqlCommand("INSERT INTO tblProducts (productName, isForSale, categoryID, isLimitedStock, stockCount, description, weightKG, basePrice, dateCreated) VALUES (@p_name, " + isForSale + ", " + selectedCatID + ", " + isLim + ", " + prodStockCount + ", '', 0, 0, getDate())", cn)) 
          { 
           cmd.Parameters.Add("@p_name", SqlDbType.VarChar, 255).Value = prodName; 
           cmd.ExecuteNonQuery(); 
          } 
         } 

        } 

       } 
       else 
       { 
        // Load the menu structure 
        tree = navigation.loadMenuData(cn, tree, dict, dicIndexes); 
        tree.loadToListBox(dict, dicIndexes, parent); 
       } 
      } 
     } 
    } 
} 

我的aspx页面:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="productAdd.aspx.cs" Inherits="********.productAdd" 
    title="Add a Product" 
    MasterPageFile="../MasterPages/AdminMaster.master" 
%> 

<asp:content id="Content2" contentplaceholderid="headContent" runat="server"> 
<SCRIPT LANGUAGE="JavaScript"> 

    function IsNumeric(input) { 
     return !isNaN(parseInt(input)); 
    } 
    function validateStock(oSrc, args) { 
     // Required 
     if (document.getElementById("<%=limitedStock.ClientID %>").checked == false) { 
      args.IsValid = true; 
     } 
     // Check if numeric 
     else if (IsNumeric(args.Value) == true) { 
      args.IsValid = !(parseInt(args.Value) < 0); 
     } else { 
     args.IsValid = false; 
     } 
    } 
    function showHide() { 

     var stockTable = document.getElementById("stockOnOff"); 

     if (document.getElementById("<%=limitedStock.ClientID %>").checked) { 
      stockTable.style.display = "block"; 
     } else { 
      stockTable.style.display = "none"; 
     } 
    } 
</SCRIPT> 
</asp:content> 

<asp:content id="Content1" contentplaceholderid="mainContent" runat="server"> 

    <form runat="server" action="productCats.aspx?action=new&mid=2"> 
     <div class="subHead">Basic Details</div> 
     <table class="settingTable"> 
      <tr> 
       <td colspan="2"><b>Product Name</b></td> 
      </tr> 
      <tr> 
       <td> 
        <asp:TextBox ID="productName" runat="server" CssClass="tbox"></asp:TextBox> 
        <asp:RequiredFieldValidator runat="server"       
           id="ValidatorName" 
           ControlToValidate="productName" 
           ErrorMessage="You need to enter a product name" 
           display="Dynamic" /> 
       </td> 
      </tr> 
      <tr> 
       <td colspan="2"><b>Category</b></td> 
      </tr> 
      <tr> 
       <td> 
        <asp:ListBox SelectionMode="Single" Rows="8" id="parent" runat="server" CssClass="tbox widebox"> 
         <asp:ListItem Selected="True" Text="Top Level" Value="0"></asp:ListItem> 
        </asp:ListBox> 
        <asp:RequiredFieldValidator runat="server" 
           id="RequiredFieldValidator1" 
           ControlToValidate="parent" 
           ErrorMessage="You need to select a parent" 
           display="Dynamic" /> 
       </td> 
      </tr> 
     </table> 

     <div class="subHead">Stock Options</div> 
     <table class="settingTable"> 
      <tr> 
       <td colspan="2"><b>Limited Stock</b></td> 
      </tr> 
      <tr> 
       <td width="50" align="center"><asp:CheckBox ID="limitedStock" runat="server" /></td> 
       <td>If checked this product will have a limited stock</td> 
      </tr> 
     </table> 
     <table class="settingTable" id="stockOnOff" style="display:none;"> 
      <tr> 
       <td colspan="2"><b>Stock Count</b></td> 
      </tr> 
      <tr> 
       <td> 
        <asp:TextBox ID="stockCount" runat="server" CssClass="tbox smallBox"></asp:TextBox> 
        <asp:CustomValidator id="stockValidator" runat=server 
         ControlToValidate = "stockCount" 
         ErrorMessage = "Enter a value of at least 0" 
         ValidateEmptyText="true" 
         ClientValidationFunction="validateStock" > 
        </asp:CustomValidator> 
       </td> 
      </tr> 
     </table> 

     <div class="subHead">Other</div>   
     <table class="settingTable"> 
      <tr> 
       <td colspan="2"><b>Hide</b></td> 
      </tr> 
      <tr> 
       <td width="50" align="center"><asp:CheckBox ID="hidden" runat="server" /></td> 
       <td>If checked, the product will be hidden for visitors</td> 
      </tr> 

     </table> 

     <asp:Button id="id" text="Add Product" runat="server" /> 

    </form> 



</asp:content> 
+0

你的web场中运行,作为错误中提到?这是一个至关重要的细节。 – Oded 2010-08-31 12:33:15

+0

不,它只是在测试服务器上,以前从未使用过网络农场。 – 2010-08-31 12:36:59

回答

2

你需要做的是将machineKey添加到您的web.config文件,你可以用这个工具来生成密钥

http://aspnetresources.com/tools/machineKey

我得到这个偶然,它是当我将应用程序池配置为使用2个或更多进程时。由于每个请求可以返回到任何进程,因此它需要相同的MachineKey来解码视图状态信息。

样品

<system.web> 
    <machineKey validationKey="abc" decryptionKey="xyz" validation="SHA1" decryption="AES" /> 
</system.web> 
+0

仍然不幸! – 2010-08-31 13:44:39

+0

您是否将它发布回同一页面,即您已在表单中指定了该操作。如果您发布到另一个页面,这就是视图状态无法验证的原因。添加到您的productscat.aspx.vb指令'<%@ Page EnableViewStateMac =“false”%>'。这是不安全的,但应该工作 – 2010-08-31 14:21:56

+0

是的,在看你的代码时张贴到另一个页面 – 2010-08-31 14:22:55