Saturday, February 1, 2014

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack ASP.NET

While I was debugging an ASP.NET Application, I wanted to get an object values I got this error message instead:

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

This problem occurs when using Response.Redirect or Server.Transfer method, because the Response.End method ends the page execution and shifts the execution to the Application_EndRequest event in the application's event pipeline. The line of code that follows Response.End is not executed.

This problem occurs in the Response.Redirect and Server.Transfer methods because both methods call Response.End internally.

There are 3 Solutions for this problem use just one of them:
  • For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest() method instead of Response.End to bypass the code execution to the Application_EndRequest event.
  • For Server.Transfer, use the Server.Execute method instead.
  • For Response.Redirect, use an overload, Response.Redirect(String url, bool endResponse) that passes false for the endResponse parameter to suppress the internal call to Response.End.


Source: https://www.nilebits.com/blog/2011/11/unable-to-evaluate-expression-because-the-code-is-optimized-or-a-native-frame-is-on-top-of-the-call-stack-asp-net/