Question

I was following this post on email confirmation except for ASP.NET. The following code is causing a

Exception Details: System.Threading.ThreadAbortException: Thread was being aborted.

The page is marked Async:

<%@ Page Title="Register" Async="true" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Register.aspx.cs" Inherits="AlphaFrontEndSiteASP.Account.Register" %>

The code is:

public partial class Register : Page
    {
        protected async void CreateUser_Click(object sender, EventArgs e)
        {
            try
            {
                string confirmationToken = CreateConfirmationToken();
                var user = new ApplicationUser
                {
                    UserName = UserName.Text,
                    CompanyName = CompanyName.Text,
                    emailAddress = emailAddress.Text,
                    FirstName = FirstName.Text,
                    LastName = LastName.Text,
                    ConfirmationToken = confirmationToken,
                    IsConfirmed = false
                };

                var manager = new UserManager();
                var result = await manager.CreateAsync(user, Password.Text);
                if (result.Succeeded)
                {
                    SendEmailConfirmation(emailAddress.Text, UserName.Text, confirmationToken);
                }
                Response.Redirect("~/Default.aspx");
            }
            catch (Exception ex)
            {
                common c = new common();
                c.LogError(ex.Message, "Register.aspx.cs" + " - " + this.GetType().FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name);
            }

 private string CreateConfirmationToken()
        {
            return Guid.NewGuid().ToString();
        }

        private void SendEmailConfirmation(string to, string username, string confirmationToken)
        {
            common c = new common();
            c.SendMail("foo@foo.net", to, username, confirmationToken + Environment.NewLine + "http://blah.com/Activate.aspx?confirmationCode= " + confirmationToken);
        }

Does anyone have any ideas why?

Was it helpful?

Solution

By design - Response.Redirect stops request processing by aborting the thread:

Redirect calls End which throws a ThreadAbortException exception upon completion.

  ....
  Response.Redirect("~/Default.aspx");
 }
 catch (Exception ex)

Depending on you other processing you can either

  • specify false as second argument of other Redirect override
  • ignore/no log ThreadAbortException in that piece of code
  • redesign code to do redirect differently.

Note: if you use ASP.Net MVC it's Controller.Redirect does not throw exception.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top