Subscribe to Feed

28Apr

Email Account Activation with ASPNET Membership API

Posted by admin as Asp.Net

 

In this post, lets talk about how to use ASP.net membership api to implement activating user account by confirming with an email (the approach that you usually see on several websites). I assume that you have already configured your membership database and have a working smtp server that can send emails. (If you have questions about how to configure membership database refer to the MSDN article Walkthrough: Creating a Web Site with Membership and User Login)

Now lets create our login.aspx page that has both login and register new users functionality. We will start with dropping Login Control and CreateUserWizard Control onto our login page.

If your Membership configuration settings are configured properly, Login control should work fine with out any changes. All we concerned about in this article is update the CreateUserWizard control’s behavior so that it can send a mail to the users provided email address after the user account is created.

Add a onCreatedUser event to your CreateUserWizard control. You can manually add it in html or double click on the CreateUserWizard control in Visual Studio’s design view and it will add this for you. And do not forget to set the CreateUserWizard control’s DisableCreatedUser property to true.
Here is how my LogIn.aspx page now looks like.

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Login</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:Login ID="Login1" runat="server">
        </asp:Login>
        <asp:CreateUserWizard ID="CreateUserWizard1" runat="server"
            oncreateduser="CreateUserWizard1_CreatedUser" DisableCreatedUser="true">
            <WizardSteps>
                <asp:CreateUserWizardStep runat="server" />
                <asp:CompleteWizardStep runat="server" />
            </WizardSteps>
        </asp:CreateUserWizard>
    </div>
    </form>
</body>
</html>

 

And in the code behind page for our LogIn.aspx page, we need to configure the CreateUserWizard control to send an email to the new user with instructions on how to verify their account. In particular, we will include a link in the email to the ActivateUser.aspx. The below code essentially grabs all the required information (Email Address, Name) from the entered by user in CreateUserWizard and sends an email with the UserId guid as activation key and a link pointing to the ActivateUser.aspx page.

And here is how our Login.aspx.cs looks like.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Text;
using System.Net.Mail;

public partial class Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    { }

    protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)
    {
        string userName = CreateUserWizard1.UserName;
        string emailAddress = CreateUserWizard1.Email;

        // Lets get the user's id
        Guid userId = (Guid)Membership.GetUser(userName).ProviderUserKey;

        // Now lets create an email message
        StringBuilder emailMessage = new StringBuilder();
        emailMessage.Append("Thank you for creating an account with YourDomain.com");
        emailMessage.Append("<br />");
        emailMessage.Append("Please click the below link to activate your account <br />");
        emailMessage.Append(string.Format("<a href='http://www.YourDomain.com/ActivateUser.aspx?userName{0}&Id={1}'>Activate {0} </a>", userName, userId.ToString()));
        MailMessage email = new MailMessage();
        email.From = new MailAddress("noReply@YourDomain.com");
        email.To.Add(new MailAddress(emailAddress));
        email.Subject = "Please activate your account with YourDomain";
        email.Body = emailMessage.ToString();
        email.IsBodyHtml = true;

        // Send the email
        SmtpClient client = new SmtpClient();
        client.Send(email);

        // Redirecto to What ever page
        Response.Redirect("Default.aspx", true);
    }
}
 

 

System.Net.Mail reads SMTP configuration data out of the standard .NET configuration system (so for ASP.NET applications you’d configure this in your application’s web.config file).  Here is an example of how to configure it

 

 <system.net>
    <mailSettings>
      <smtp from="test@foo.com">
        <network host="smtpserver1" port="25"
                 userName="username"
                 password="secret"
                 defaultCredentials="true" />
      </smtp>
    </mailSettings>
  </system.net>

 

The MembershipUser class has IsLockedOut and IsApproved properties. The IsLockedOut property is read-only. There is no mechanism to programmatically lock out a user; to unlock a user, use the MembershipUser class’s UnlockUser method. The IsApproved property is readable and writeable. To save any changes to this property, we need to call the Membership class’s UpdateUser method, passing in the modified MembershipUser object. And now when the user click the activation link in his email, we should change the user status in isApproved to true and redirect him to the confirmation page. Our ActivateUser.aspx does not have any code in the .aspx page except a routine in PageLoad that validates the user. Here is how out ActivateUser.aspx and its code behind looks like.

ActivateUser.aspx

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ActivateUser.aspx.cs" Inherits="ActivateUser" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>ActivateUser</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    </div>
    </form>
</body>
</html>

 

ActivateUser.aspx.cs : Here, we get the UserId and his email address as QueryString parameters and use membership api to activate the user.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class ActivateUser : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Lets Activate the User
        if (String.IsNullOrEmpty(Request.Params["Id"]))
        {
            // We do not have the userId. Redirect some where
            Response.Redirect("ErrorPage.aspx");
        }
        else
        {
            // We have a userId.
            try
            {
                Guid userId = new Guid(Request.Params["Id"]);
                MembershipUser user = Membership.GetUser(userId);
                // Activate the user
                user.IsApproved = true;
                // Update the user activation
                Membership.UpdateUser(user);

                // We success fully activate the user. Redirect somewhere
                Response.Redirect("Welcome.aspx", true);
            }
            catch
            {
                // Error. Redirect some where
                Response.Redirect("ErrorPage.aspx");
            }
        }
        // We should never reach here. Just in case redirect some where
        Response.Redirect("Default.aspx", true);
    }
}

 

And that’s it, your are now all set to activate users via Email Message.

Hope this helps someone

Ctrl+F5

56 Responses to Email Account Activation with ASPNET Membership API

Niki

January 30th, 2010 at 3:49 pm

Thank you that was extremely clear and helpful

Semih

February 10th, 2010 at 12:14 pm

Thank you

Simon

February 26th, 2010 at 11:16 pm

Wonderful!

Oras

April 28th, 2010 at 9:09 am

Extremely GREAT. I’m so grateful for this clear tutorial.

Mike

May 22nd, 2010 at 2:35 am

This is great. It really helped…..Good work

Imanuzzaman

July 12th, 2010 at 5:14 am

Can you provide us this tutorial working project files. Thank you

cem

August 2nd, 2010 at 2:37 pm

I think also that is a good explication about the user’s activation.
I have some Idea about it,but your approach is very well than mine.

Thanks a lot.

test

August 12th, 2010 at 2:01 am

test

Arpit

September 10th, 2010 at 10:46 am

I got error “Failure sending mail” while executing Client.send(mail).Please help!!

Amr

November 17th, 2010 at 9:36 pm

really u r own for your munificence

Amr

November 18th, 2010 at 1:57 am

i got error in Membership.UpdateUser(user)

@Ctrlf5

December 8th, 2010 at 10:01 pm

@Amr, what is the error you are seeing? Can you add the stack trace?

Walter

February 11th, 2011 at 9:58 pm

Really appreciate this posting. A tremendous timesaver for implementing this feature.

space

February 28th, 2011 at 7:01 pm

hey, everything worked for me, but on activation page it redirects to the page in the catch statement. i don’t know why since the membership got updated and i could log in on the newly created user.

@Eshe

April 28th, 2011 at 7:36 am

So clear and very helpful…Thank you

George

August 8th, 2011 at 1:49 am

Thank you.

Jeff

August 24th, 2011 at 8:09 am

Thank you for this clear and helpful tutorial

Graphite

September 14th, 2011 at 8:38 pm

On line poker is surely an great Online game you could make Money using that, and bring in more revenue when you use Rakeback Deals.

hotDutProgrammer

September 29th, 2011 at 6:25 am

Im gettin this error “The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required”. please helpts urgent.

Radeon

October 7th, 2011 at 5:07 am

Thx
Great tutorial.

Nobody

November 27th, 2011 at 10:16 am

i cant send the email.getting internal error “The remote name could not be resolved: ’smtpserver1′” please can someone help me out?

ehh

December 27th, 2011 at 5:10 pm

thanks a lot. it is realy great tutorial.
I also experienced the redirection after activation to the page in the catch statement ( THE ERROR PAGE) ? please help .. thanks

ahajou

January 1st, 2012 at 10:37 am

Man the user is still active.

Need to add code to deactivate the user before sending the email.

just add the below code to the createduser event:
//De-activate user
{
MembershipUser user = Membership.GetUser(CreateUserWizard1.UserName);
// De-Activate the user
user.IsApproved = false;
// Update the user activation
Membership.UpdateUser(user);
}

thanks for the post clear and compact really helpful and appreciated.

Juan

January 17th, 2012 at 3:17 pm

ddd

Suba

February 8th, 2012 at 6:22 am

Thanks for this code. It saved my hours.

freddy

April 2nd, 2012 at 2:40 am

Hi This is very good.
Do you still respons to this code ?

Ahmed Naji

April 9th, 2012 at 2:25 am

Clear & nice
Thx.

Kee

May 8th, 2012 at 5:31 am

can i know how to code Email Account Activation with ASPNET Membership API without using createuserwizard?

Anirban Das

June 28th, 2012 at 2:24 am

thanks

1

July 12th, 2012 at 7:34 pm

-1′

Roger Willcocks

August 26th, 2012 at 9:48 pm

Being redirected to the error page is occurring because Response.Redirect causes a ThreadAbortException to be raised.

You need to be this instead

try {

Response.Redirect(”Welcome.aspx”, true);
}
catch(ThreadAbortException)
{
}
catch
{
// Error. Redirect some where
Response.Redirect(”ErrorPage.aspx”);
}

omer

October 3rd, 2012 at 9:32 pm

Thanks for codes. Roger thank you too for additional information. Together working without error.

neha

October 23rd, 2012 at 11:02 pm

plz tell me how to configure the website with membership . it shows the error “unable to connect to sql server” here
Guid userId = (Guid)Membership.GetUser(userName).ProviderUserKey;

Serguei

November 30th, 2012 at 5:52 am

I added the next code to Register Action:

// if there is user with such name and hi is not approved - DELETE HIM!
MembershipUser user = Membership.GetUser(model.Email);
if (user != null)
{
if (!user.IsApproved)
Membership.DeleteUser(model.Email, true);
}

Thenignon

December 12th, 2012 at 10:49 pm

Mask: You’ll want to prevent laser toner particles from entering your throat and lungs If it was an eCourse then take the time and rewrite it and get it out there pulling for you So one need not have to despise reason in order to be spiritual in his approach Ghost is a creaky 15-year-old and Betty is a spry 10-year-old, and we had quite a visit to the vet last month
When you are hurt or frightened (physically, emotionally, or mentally), a message goes to your brain stem, the threat is recognized, fear is created, and you move into the same mode ? fight, flight, or freeze Breaking a corona wire can be a costly mistake Is there anyone out there who doesn’t feel like they have some purpose on this Earth? Do you feel embarrassed by thinking that, feel it’s too lofty? Some voices in your head telling you all those lovely things, who do you think you are?, yeah right, you, hah! and on and on Once you’ve chosen a name, try it out for a day or so

Frank Gore Elite Jersey
Kids A.J. Green Jersey
Matt Ryan Nike Jersey

hsl

February 10th, 2013 at 6:34 am

i need something a bit different wich is when user registers he recieves an email to activate your account BUT needs to wait to admin aproval so it register but it needs to wait to a admin to aprove the account, when admin aproves he recieves another mail saying account was aproved and ready to use

if you can contact me by mail i would like to implement this

the diet solution reviews

April 9th, 2013 at 9:01 pm

This article will help the internet users for building up new weblog or even a weblog from start to end.

Http://Suplementosfantasticos.wordpress.com/

July 2nd, 2013 at 11:50 am

You will also lower your cholesterol and risk of heart disease because you will be eliminating
unhealthy fats from your diet. Instead of wolfing down your food you chew it 20 to 30 times
or more until it becomes a liquid in your mouth and mixed well
with saliva. Just as importantly, Tru - Sculpt Body Shaping is safe,
largely painless, can be performed on-site at reputable medical spas, and requires no anesthesia.

produtosemagrecerblog.wordpress.com

September 23rd, 2013 at 5:02 pm

Thaanks for the good writeup. It in truth was a amusement account
it. Look advanced to more added agreeable from you!
However, how could we be in contact?

wordpress.Com

October 3rd, 2013 at 4:15 pm

This design is incredible! You obviously know howw to keep a reader entertained.
Between your wit and youhr videos, I was almost moved to start my own
blog (well, almost…HaHa!) Great job. I really enjoyed what you had to say,
and more than that, how youu presented it. Too cool!

Niklas

October 18th, 2013 at 2:37 am

I know this if off topic butt I’m looking into starting my own weblog and was wondering what all is needed to
get setup? I’m assuming having a blog like yours would cost a pretty
penny? I’m not very web smart so I’m not 100% sure. Any tips or advice would be greatly appreciated.

Appreciate it

Brooke

October 31st, 2013 at 2:12 am

I don’t drop a comment, however I browsed a
few of the responses on Email Account Activation with ASPNET Membership API | Ctrl+F5.
I actually do have a couple of questions for you if you
tend not to mind. Is it only me or does it look like some of these responses look like
they are coming from brain dead folks? :-P And, if you are posting on other sites, I’d
like to follow anything fresh you have to post. Would you post a list of evewry one of all your social pages like your
linkedin profile, Facebook page or twitter feed?

queimadoresgordura.tumblr.com

November 19th, 2013 at 2:58 am

We’re a gaggle of volunteers and opening a new scheme in our community.
Your web site offered us with helpful information to work on.

You have performed a formidable job and our entire group shall be thankful to you.

Wilfredo

November 22nd, 2013 at 8:28 am

This piece of writing will assist the internet viewers
for ccreating new website or even a blog from start to
end.

Domingo

November 22nd, 2013 at 5:12 pm

That iis really attention-grabbing, You’re a very skilled blogger.
I have joined your feed and look forward to searching for extra of your excellent post.

Also, I’ve shared your web site in my social networks

dicasnutricao.tumblr.com

December 1st, 2013 at 5:18 pm

Have you ever thought about writingg an ebook or guest authoring on other blogs?

I hage a blog based upon on the same subjects you discuss and would
really like tto have you share some stories/information.
I know my audience would enjoy your work. If you aare even remotely
interested, feel free to shoot me an email.

__

December 6th, 2013 at 11:27 am

Hi there! I simply wish to give an enormous thumbs up for the good info you could have here on
this post. I can be coming back to your weblog for more soon.

receitasdieta.tumblr.com

December 7th, 2013 at 2:45 am

Hi there, of course thyis post is actually good and I have learned lot of things from it regardding blogging.

thanks.

Caridad

December 8th, 2013 at 3:28 am

Heloo just wanted to give you a brief heads up and let you know a few of the pictures
aren’t loading properly. I’m not sure why but I think its a linking issue.
I’ve tried it in two different browsers and both
show the same outcome.

_____

December 10th, 2013 at 7:14 pm

If you would like to grow your experience only keep visiting
this web page and be updated with the hottest news update posted here.

http://suplementosblogquero.blog.com

December 17th, 2013 at 2:02 am

This is a topic which is near to my heart… Many thanks! Exactly where are
your conttact details though?

Mathias

December 22nd, 2013 at 3:12 am

I know this if off topic but I’m looking into starting my own blog and was curious what all is required to get set up?
I’m assuming having a bog like yours would cost a pretty penny?
I’m not very internet smart so I’m not 100% positive.

Any recommendations or advice would be greatly appreciated.
Cheers

adiphenemax.com

December 28th, 2013 at 6:25 am

You cann definitely see your expertise in the work you write.
Thhe arena hopes for even more passionate writers like you
who aren’t afraid to say how they believe.
All the time go after your heart.

windows 8 working activator

January 1st, 2014 at 7:32 am

Ahaa, its fastidious conversation about this paragraph here
at this website, I have read all that, so at this time me also commenting at this place.

co

March 15th, 2014 at 10:26 pm

J’

sex toys for women

March 17th, 2014 at 6:36 am

If some one needs expert view concerning blogging then i recommend him/her to visit
this weblog, Keep up the fastidious job.

Comment Form

 

 

Recent Comments