[asp.net] Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

I am getting the error:

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

I have redirected to a new page in repeater's itemcommand event. The error occurs at the line:

string url = "~/Galleries/AlbumImageList.aspx?UId=" + this.UserId.ToString() + "&AlbumId=" + e.CommandArgument.ToString();
Response.Redirect(url);

Can anybody please help me? Is anything wrong there? The _COMPlusExceptionCode is -532459699.

This question is related to asp.net .net-3.5 response.redirect

The answer is


Resolution

To work around this problem, use one of the following methods:

Symptoms

If you use the Response.End, Response.Redirect, or Server.Transfer method, a ThreadAbortException exception occurs. You can use a try-catch statement to catch this exception.

Cause

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.

Status

This behavior is by design.

Properties

Article ID: 312629 - Last Review: August 30, 2012 - Revision: 4.0

Applies to

  • Microsoft ASP.NET 4.5
  • Microsoft ASP.NET 4
  • Microsoft ASP.NET 3.5
  • Microsoft ASP.NET 2.0
  • Microsoft ASP.NET 1.1
  • Microsoft ASP.NET 1.0

Keywords: kbexcepthandling kbprb KB312629

Source: PRB: ThreadAbortException Occurs If You Use Response.End, Response.Redirect, or Server.Transfer


In a bug I was investigating there was a Response.Redirect() and it was executing in an unexpected location (read: inappropriate location - inside a member property getter method).

If you're debugging a problem and experience the "Unable to evaluate expression..." exception:

  1. Perform a search for Response.Redirect() and either make the second parameter endResponse = false, or
  2. Temporarily disable the redirect call.

This was frustrating as it would appear to execute the Redirect call before the "step through" on the debugger had reached that location.


This problem may be a result when you have a razor page in mvc with a model that has some validation rules. When you post from a form and you forget to display validation errors on some field, then this message might come up. Speculation: this could be if the method you are posting to is different and used by other sources or resides in a different place than the method serving the original request.

So because it's different, it can't return to the original page to display or handle the errors because the excecution and model state is not the same (something like that).

It can be slightly difficult to discover, but easy mistake to do. Make sure your recieving method actually validates all possible ways to post to it.

for instance, even if you have serverside validation that actually makes it impossible to write in the form a string that is bigger than the max allowed by your validation, there could be other ways and sources that post to the recieving method.


Please check this link for the reason behind this issue and solution for the error:

http://support.microsoft.com/kb/312629/EN-US/

Microsoft Support Article:

PRB: ThreadAbortException Occurs If You Use Response.End, Response.Redirect, or Server.Transfer Print Print Email Email

To work around this problem, use one of the following methods: 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 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.

For example: Response.Redirect ("nextpage.aspx", false);

If you use this workaround, the code that follows Response.Redirect is executed. For Server.Transfer, use the Server.Execute method instead.


Use this, works for me always.

Response.Redirect(Request.RawUrl, false);

Here, Response.Redirect(Request.RawUrl) simply redirects to the url of the current context, while the second parameter "false" indicates to either endResponse or not.


Also You Can Use Server.Execute


use this code solve the problem:

string path = AppDomain.CurrentDomain.BaseDirectory.ToString() + "Uploadfile\\" + fileName;
System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] bt = new byte[fs.Length];
fs.Read(bt, 0, (int)fs.Length);
fs.Close();
Response.ContentType = "application/x-unknown/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + fileName;+ "\"");
try
{
    if (bt != null)
    {
        System.IO.MemoryStream stream1 = new System.IO.MemoryStream(bt, true);
        stream1.Write(bt, 0, bt.Length);
        Response.BinaryWrite(bt);
        //Response.OutputStream.Write(bt, 0, (int)stream1.Length);
        Response.Flush();
        // Response.End();
    }
}
catch (Exception ex)
{
    Response.Write(ex.Message);
    throw ex;
}
finally
{
    Response.End();
}

I had this same problem too, and it was tricky. For me, it was because I'm using Ext.Js javascript library. If you are doing a response.redirect in server-side code that you accessed in an Ajax call, there are problems. Ext.js has a workaround with their Ext.Redirect method.


Just encase someone else ran into the issues I did I was using Response.End() an async trigger button

<asp:AsyncPostBackTrigger ControlID="btn_login" />

in an update panel. I switched to regular post back not the best but it worked.

<asp:PostBackTrigger ControlID="btn_login" />. 

Since I was only redirecting on the page this was a viable solution.


If you are using Update Panel and link button to download excel is inside the panel than add postback trigger

<asp:PostBackTrigger ControlID="lnkTemplate" /> 

and in Code behind inside click event

string ServerPath = System.Configuration.ConfigurationManager.AppSettings["FilePath"] + "Template.xlsx";
System.IO.FileInfo file = new System.IO.FileInfo(Server.MapPath(ServerPath));

HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
            HttpContext.Current.Response.ContentType = "application/octet-stream";
 HttpContext.Current.Response.TransmitFile(file.FullName);
 HttpContext.Current.Response.Flush();
 HttpContext.Current.ApplicationInstance.CompleteRequest();

Request.Redirect(url,false);

false indicates whether execution of current page should terminate.


Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to .net-3.5

Get first element from a dictionary redistributable offline .NET Framework 3.5 installer for Windows 8 How to read an entire file to a string using C#? HTTP Error 500.22 - Internal Server Error (An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.) Change the Textbox height? How to get current date in 'YYYY-MM-DD' format in ASP.NET? C# Numeric Only TextBox Control Will the IE9 WebBrowser Control Support all of IE9's features, including SVG? Use LINQ to get items in one List<>, that are not in another List<> Get Absolute URL from Relative path (refactored method)

Examples related to response.redirect

Redirecting new tab on button click.(Response.Redirect) in asp.net C# go to link on button click - jquery Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack Why do I get "Cannot redirect after HTTP headers have been sent" when I call Response.Redirect()? Response.Redirect to new window Response.Redirect with POST instead of Get?