Why Response.Redirect causes System.Threading.ThreadAbortException?

前端 未结 10 1870
误落风尘
误落风尘 2020-11-22 15:00

When I use Response.Redirect(...) to redirect my form to a new page I get the error:

A first chance exception of type \'System.Threading.ThreadAbortEx

10条回答
  •  无人共我
    2020-11-22 15:15

    I know I'm late, but I've only ever had this error if my Response.Redirect is in a Try...Catch block.

    Never put a Response.Redirect into a Try...Catch block. It's bad practice

    As an alternative to putting the Response.Redirect into the Try...Catch block, I'd break up the method/function into two steps.

    1. inside the Try...Catch block performs the requested actions and sets a "result" value to indicate success or failure of the actions.

    2. outside of the Try...Catch block does the redirect (or doesn't) depending on what the "result" value is.

    This code is far from perfect and probably should not be copied since I haven't tested it.

    public void btnLogin_Click(UserLoginViewModel model)
    {
        bool ValidLogin = false; // this is our "result value"
        try
        {
            using (Context Db = new Context)
            {
                User User = new User();
    
                if (String.IsNullOrEmpty(model.EmailAddress))
                    ValidLogin = false; // no email address was entered
                else
                    User = Db.FirstOrDefault(x => x.EmailAddress == model.EmailAddress);
    
                if (User != null && User.PasswordHash == Hashing.CreateHash(model.Password))
                    ValidLogin = true; // login succeeded
            }
        }
        catch (Exception ex)
        {
            throw ex; // something went wrong so throw an error
        }
    
        if (ValidLogin)
        {
            GenerateCookie(User);
            Response.Redirect("~/Members/Default.aspx");
        }
        else
        {
            // do something to indicate that the login failed.
        }
    }
    

提交回复
热议问题