5

我是 aspx 网络表单的新手。

我想在我的 Web 应用程序中捕获一个特定的异常 - Validation of viewstate MAC failed.
我试过这个(在 Global.asax.cs 中):

protected void Application_Error(object sender, EventArgs e)
{
  HttpException lastErrWrapper = Server.GetLastError() as HttpException;

  if ((uint)lastErrWrapper.ErrorCode == 0x80004005)
  {
      // do something
  }         
}

问题是它捕获了所有未处理的 HttpExceptions。

实现这一目标的最佳方法是什么?


编辑:

在进一步检查这个问题时,我发现内部异常是 a ViewStateException,但它似乎没有特定的“errorCode”属性

谢谢

4

2 回答 2

5

这应该这样做

if ((lastErrWrapper != null) && (lastErrWrapper.InnerException != null) 
  && (lastErrWrapper.InnerException is ViewStateException)
{
}

HttpException 旨在使所有与 HTTP/web 相关的东西都可以被一个处理程序捕获,因此您需要深入研究并查看原始异常。ViewStateException 可能会捕获其他几个与视图状态相关的错误,但这可能没问题。

于 2012-08-30T13:48:42.287 回答
1

以下是我们为帮助应对 globa.asax 中的 ViewState 错误而实施的内容:

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)

    Dim context As HttpContext = HttpContext.Current
    Dim exception As Exception = Server.GetLastError

    'custom exception handling:
    If Not IsNothing(exception) Then

        If Not IsNothing(exception.InnerException) Then

            'ViewState Exception:
            If exception.InnerException.GetType = GetType(ViewStateException) Then
                'The state information is invalid for this page and might be corrupted.

                'Caused by VIEWSTATE|VIEWSTATEENCRYPTED|EVENTVALIDATION hidden fields being malformed
                ' + could be page is submitted before being fully loaded
                ' + hidden fields have been malformed by proxies or user tampering
                ' + hidden fields have been trunkated by mobile devices
                ' + remotly loaded content into the page using ajax causes the hidden fields to be overridden with incorrect values (when a user navigates back to a cached page)

                'Remedy: reload the request page to replenish the viewstate:
                Server.ClearError()
                Response.Clear()
                Response.Redirect(context.Request.Url.ToString, False)
                Exit Sub
            End If

        End If

    End If

End Sub
于 2014-02-15T12:00:25.310 回答