Develop your own blog. NET version step by step (3. Register for login), blog. net

Source: Internet
Author: User
Tags mailmessage smtpclient

Develop your own blog. NET version step by step (3. Register for login), blog. net
Preface

Main features and features of this blog:
1. compatible with various terminals, especially mobile phones.
Second, we will use a lot of html5.
Third, import the best articles of the blog Park and classify them. (Do not seal me)
4. As a plug-in, any technical articles on the website can be forwarded to this blog.

So I plan to write a series: building my blog step by step

1. Develop your own blog. NET version step by step (1. page layout, blog migration, and data loading)

2. Develop your own blog. NET version step by step (2. Comment function)

3. Develop your own blog. NET version step by step (3. register the logon function)

4. Develop your own blog. NET version step by step (4. Article publishing function)

5. Develop your own blog. NET version step by step (5. Search function)

6. Develop your own blog. NET version step by step (6. Mobile compatibility)

 

Demo address: http://blog.haojima.net/group sharing source code: 469075305

 

Today, we mainly analyze registration and logon. With regard to the implementation of these two functions, I believe that everyone has their own experience. It is easy to say that they can be done easily.

To put it bluntly, registration is to insert a piece of data into the database, and login is to query whether the data exists in the database. Of course, you can also have your own rule verification. For example, the user name cannot be repeated, and the password cannot be blank...

To prevent malicious registration, you can add an email address for verification. So What email should we use to send an email notification? 163 Mail? QQ Mail ?, Then we have lost our face as the webmaster. At least I have an enterprise email address related to your domain name. No (* ^__ ^ *)

Here I will share with you a free enterprise mailbox. Http://wanwang.aliyun.com/promotion/free-times/

If you have applications for free enterprise, I will not introduce them too much here. After applying, bind your domain name and you will be OK.

Next, we will analyze the implementation of my registration and login functions.

Get activation code and Activation

First, let's talk about how to get the activation code and how to activate it. What is the activation code first? The activation code is mainly used for verification. First, prove that the mailbox user exists, which can effectively prevent malicious registration. 2. Only mailbox users can modify user information, such as passwords. Because there are many "possibly" places where the activation code is needed, we separate the two methods.

Get activation code

Obtain the activation code, which is, in fact, a random number, First saved to the Session, and then sent to the registered email. Of course, there is an important point here, that is, the mail sending help class.

Public class EmailHelper {# region Eail attribute private string _ mailFrom = "system@haojima.net "; /// <summary> // sender // </summary> public string mailFrom {get {return _ mailFrom;} set {_ mailFrom = value ;}} /// <summary> /// recipient /// </summary> public string [] mailToArray {get; set ;} /// <summary> /// CC // </summary> public string [] mailCcArray {get; set ;} /// <summary> /// title /// </summary> Public string mailSubject {get; set ;}/// <summary >/// body /// </summary> public string mailBody {get; set ;} /// <summary> /// sender's password /// </summary> public string mailPwd {get; set;} private string _ host = "smtp.haojima.net "; /// <summary> /// SMTP email server // </summary> public string host {get {return _ host;} set {_ host = value ;}} private bool _ isbodyHtml = true; // <summary> // whether the body is h Tml format // </summary> public bool isbodyHtml {get {return _ isbodyHtml;} set {_ isbodyHtml = value ;}} private string _ nickname = "hi-Blog system notifications "; /// <summary> // sender nickname /// </summary> public string nickname {get {return _ nickname;} set {_ nickname = value ;}} /// <summary> /// attachment /// </summary> public string [] attachmentsPath {get; set ;}// Priority level private MailPriority _ Priority = MailPriority. N Ormal; // <summary> // The default Priority of the Priority level is normal. // </summary> public MailPriority Priority {get {return _ Priority ;} set {_ Priority = value ;}# endregion public bool Send () {// use the specified email address to initialize MailAddress instance MailAddress maddr = new MailAddress (mailFrom, nickname ); // initialize MailMessage instance MailMessage myMail = new MailMessage (); // Add the email address if (mailToArray! = Null) {for (int I = 0; I <mailToArray. length; I ++) {myMail. to. add (mailToArray [I]. toString () ;}}// Add the email address if (mailCcArray! = Null) {for (int I = 0; I <mailCcArray. length; I ++) {myMail. CC. add (mailCcArray [I]. toString () ;}/// sender address myMail. from = maddr; // Email Subject myMail. subject = mailSubject; // The Subject content of the email is encoded in myMail. subjectEncoding = Encoding. UTF8; // email body myMail. body = mailBody; // The email Body code is myMail. bodyEncoding = Encoding. default; // mail priority myMail. priority = Priority; myMail. isBodyHtml = isbodyHtml; // Add an attachment when there is an attachment. try {If (attachmentsPath! = Null & attachmentsPath. length> 0) {Attachment attachFile = null; foreach (string path in attachmentsPath) {attachFile = new Attachment (path); myMail. attachments. add (attachFile) ;}} catch (Exception err) {throw new Exception ("An error occurred while adding the attachment:" + err);} SmtpClient smtp = new SmtpClient (); // specify the sender's email address and password to verify the sender's identity as smtp. credentials = new System. net. networkCredential (mailFrom, mailPwd); // 115 // set SMTP Mail Server smtp. host = host; // smtp. enableSsl = true; // smtp. port = 587; try {// send the email to SMTP. send (myMail); return true;} catch (System. net. mail. smtpException ex) {return false ;}}}View Code

Usage:

EmailHelper email = new EmailHelper () {mailPwd = sender password, host = email server, mailFrom = sender email, mailSubject = email title, mailBody = email body, mailToArray = new string [] {sent to}; email. send (); // Send

:

Activate

Activate, copy the activation code you received to compare with the number of data stored in the session. If they are equal, the verification is successful. Then, register the registration and change the password. (After the verification is successful, you can send an email to inform the registration successful and send the registration information to avoid the registration user forgetting to cancel the registration information)

Data Verification

Authentication is required in multiple places during registration and login. For example, the user name and password must be in a correct and non-empty email format. However, it is refreshing to use the features in MVC.

Here is my usage (for the first time ).

Feature verification: Required is not empty [Required (ErrorMessage = "UserName cannot be blank")] public string UserName {get; set ;}

We can directly mark the feature on the property. If the verification fails during data storage, a custom exception is thrown. However, there is a problem here. Our entity classes are automatically generated through tt files. The features we added will be cleared the next time the tt file is saved. However, Microsoft has long been thinking about it for us. Tt generates a partial classification. Then we can generate a classification externally to add features and then merge them automatically during compilation.

Here is background verification. Of course, we can not only verify the backend, but can shield requests that fail to pass verification directly at the front end, which can also reduce the burden on the server. What we will talk about next is "cool. The features we added in the background can be verified directly on the frontend. How can this be achieved? In fact, we can probably guess the generated html code.

First, we use a strongly typed "declaration" in the Razor View of the View ". @ Model BlogUsersSet

Then, the @ Html. TextBoxFor (t => t. UserName) in the View can directly use the lambda expression.

We can see the html code generated at the front end.

<Input class = "txt_username" data-val = "true" data-val-required = "UserName cannot be blank" id = "UserName" name = "UserName" type = "text "value =" ">

Do we understand something here? The verification information is directly included in the tag. Of course, this is only generated in the html Tag. In fact, we cannot complete the front-end verification. We need to introduce some js files provided by Microsoft if we want to automatically verify on the front-end. Jquery. validate. js jquery. validate. unobtrusive. js you can see the name and you will need to reference the jquery file before referencing it.

The verification result is OK at the front-end. It is not enough to verify it. At least you have to have a prompt. @ Html. ValidationMessageFor (t => t. UserName) automatically outputs a message indicating that the verification fails.

To sum up, use the features in MVC for verification:

First, you need to add features in the model class in the background: for example, [Required (ErrorMessage = "UserName cannot be blank")] public string UserName {get; set ;} (Only background verification is completed here)

Second, we need to introduce two js files at the front end: jquery. validate. js jquery. validate. unobtrusive. js (the front-end verification is completed here)

Third, generate controls and verification prompts in the View File. @ Html. TextBoxFor (t => t. UserName) // generate the control @ Html. ValidationMessageFor (t => t. UserName) // verify the message

:

Demo address: http://blog.haojima.net/UserManage/Regis

The most important verification code, activation code, and data verification for registration and logon have been analyzed. Let's briefly describe how to register, log on, and reset the password.

Register

The registration information includes the user name, password, nickname, and email address.

User name: It is required. It is not empty and not repeated. It is mainly used to verify the link in the login and url. Such as: zhaopei in the http://blog.haojima.net/zhaopei/1.html.

Password: required or not. It is mainly used to verify logon.

Nickname: It is optional. It is mainly used to display your personal homepage in a friendly way so that others can remember you. If it is null, replace it with the user name.

Email: It is required. It is not empty and is not repeated, it is mainly used to verify activation and password resetting during registration, and to verify activation and comment email notifications, intra-site message notifications (comment email notification intra-site Message notification function is not completed yet)

:

Login

1. If logon is successful. Save the logon user information to the session.

2. If "Automatic Logon" is selected, the user information will be saved to the client cookie. The next time session is retrieved, if the session is null, the system will check whether the cookie has valid user information.

Here, I also added an "IsLock" in the database to check whether it is locked. If malicious or illegal content is detected, it can be used to lock the user. Make it inaccessible.

:

Reset Password

Reset the password, that is, change the password.

Required fields: email address and New Password

Send the verification code to your email address and check whether the entered verification code is correct. If the password is correct, change it to the new password.

:

Summary

This section mainly analyzes and introduces the registration, logon, and password reset of blog users. Its main shared module functions include obtaining activation code, triggering activation, and data verification.

Registration process: Enter registration information-> Verification Information-> email verification-> Registration successful

Login process: Enter the login information-> database query->

1. Lock-> send email activation code-> activate-> login successful

2. Unlocked-> logon successful

Demo address: http://blog.haojima.net/UserManage/Regis (interface ugly is ugly, then beautify)

If you are interested in this article, please give me a thumbs up. Your encouragement will be my motivation. Of course, you can also join the QQ group: discussion.

If you have a better solution, don't give me some advice.

Link: http://www.cnblogs.com/zhaopei/p/4770340.html

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.