ThreadAbort使用ASP.NET身份模型

时间:2014-03-25 19:27:59

标签: c# asp.net asynchronous threadabortexception

除了ASP.NET之外,我关注this post on email confirmation。以下代码导致

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

该页面标记为Async:

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

代码是:

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);
        }

有没有人有任何想法?

1 个答案:

答案 0 :(得分:2)

按设计 - Response.Redirect通过中止线程停止请求处理:

  

重定向调用End,在完成时抛出ThreadAbortException异常。

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

根据您的其他处理,您可以

  • 指定false作为其他Redirect覆盖
  • 的第二个参数
  • 在该段代码中忽略/不记录ThreadAbortException
  • 重新设计代码以进行不同的重定向。

注意:如果您使用ASP.Net MVC,它的Controller.Redirect不会抛出异常。