简体   繁体   中英

Redirecting after click on button throws error ASP.NET

I used regular button to throw span into button. I also made onServerClick function (to handle the event).

<button id="btnCancel" runat="server" class="btn btn-default pull-right" onserverclick="btnCancel_Click"><span class="glyphicon glyphicon-remove text-magenta"></span>Cancel</button> 

This should be simple cancel button that should exit the form and noting else. But for some reason C# function throws exception on redirect.

Here is the function:

            try
        {
            Response.Redirect("StartPage.aspx");
        }
        catch (Exception ex)
        {
            NLog.LogManager.GetCurrentClassLogger().Warn("Error happened", ex);
            Response.Redirect("Error.aspx", false);
        }

Also if I just dont put try and catch block everything works fine.

Response.Redirect throws a ThreadAbortException that is caught by your exception handler. Either

  • remove the exception handler (if the real-life code is as simple as your sample, there should be no need for an exception handler) or
  • move the Response.Redirect out of the exception handler or
  • create a dedicated handler for the ThreadAbortException like this:

try
{
    Response.Redirect("StartPage.aspx");
}
catch (ThreadAbortException)
{
  // Exception is expected, do nothing
}
catch (Exception ex)
{
    NLog.LogManager.GetCurrentClassLogger().Warn("Error happened", ex);
    Response.Redirect("Error.aspx", false);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM