问题描述
看来,这两个特点都在WebMatrix中code一组辅助功能和模式走了。但是,有没有控制器的方法或意见,以完成它,所以你必须自己实现。
It appears that these two features have a set of helper functions and schema in the WebMatrix code to get going. However, there are no controller methods or views to get it done, so you have to implement yourself.
有什么样的任何地方,我可以这样code只是复制到我的应用程序?我在寻找的东西:
Is there any samples anywhere where I can just copy this code into my app? I'm looking for something to:
- 生成忘记密码电子邮件
- 生成确认电子邮件
- 忘记密码视图+控制器方法
- 重发确认邮件视图+控制器方法
推荐答案
忘记密码的功能。
有一天,我试图创建在asp.net MVC 4.我进出GOOGLE了忘记密码功能,但无法获得最佳的解决方案。我终于找到了出路。
15简单的步骤
The other day I was trying to create a "forgot password functionality" in asp.net MVC 4. I googled in and out but couldn't get the best solution. I have finally found the way out.15 simple steps
第1部分
发送密码重置通过Email信息
Part 1 Sending Password Reset Information via Email
第1步
•创建的mvc 4 C#的互联网应用模板:)
(账户及家用控制器将自动生成)
•建立并运行项目。注册和登录。
(简单的会员表将生成)
Step 1• Create Mvc 4 c# Internet application template :) (Account and home controllers will automatically be generated)• Build and run your project. Register and login.(Simple membership tables will be generated)
Everything working fine?
步骤2
•哎呀!他们不问我们的电子邮件ID,而注册!为了密码令牌发送给用户,我们需要他们的电子邮件ID!因此,让我们做一些修改数据库到服务器资源管理器! (如果妳找不到U可以preSS CTRL + ALT + S)
•展开数据连接和u会看到情侣对表。打开用户个人资料表。
添加以下栏目:
Step 2• Oops!! They don’t ask our email id while registration! In order to send password token to users we need their email id!! So let’s make a few changes in database go to server explorer! ( If u can’t find it u can press Ctrl + alt + S )• Expand "data connections" and u will see a couple of tables. Open User Profile table.Add the following columns:
- EMAILID为nvarchar(最大)
2.Details为nvarchar(最大)
步骤3
•现在去Solution Explorer中... ...型号Account模型...注册模型
•添加这两个属性的电子邮件ID和详细信息。
Step 3• Now go to Solution Explorer...Models ... Account model ... Register model• Add these two properties for Email Id and Details
//new properties
[Required]
[Display(Name="Email ID")]
public string EmailId { get; set; }
[Required]
[Display(Name = "About Yourself")]
public string Details { get; set; }
步骤4
•现在去Solution Explorer中...查看...的意见... Register.cshtml视图
•允许用户输入电子邮件ID和其他细节添加这两个属性。
Step 4• Now go to Solution Explorer…Views ... Account Views ... Register.cshtml view• Add these two properties for allowing users to enter email id and other details.
@ Html.LabelFor(M => m.EmailId)
@ Html.TextBoxFor(M => m.EmailId)
@ Html.LabelFor(M => m.Details)
@ Html.TextBoxFor(M => m.Details)
第5步
•现在去解决方案管理器... ...控制器控制器帐号注册...控制器的操作方法的版本后
•允许用户输入电子邮件ID和其他details.The变化突出添加这些属性。
Step 5• Now go to Solution Explorer…Controllers ... Account Controller ... Post version of Register controller action method• Add these properties for allowing users to enter email id and other details.The changes are highlighted.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { EmailId = model.EmailId, Details = model.Details});
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
我们为什么不重新构建并运行我们的项目?注册并填写详细信息。现在,你会被要求指定电子邮件地址,也允许用户输入电子邮件ID和其他细节。新增这些属性。
Why don’t we again build and run our project? Register and fill in the details .Now you will be asked to specify email address also .Add these properties for allowing users to enter email id and other details.
转到服务器资源管理器右键点击用户配置文件表并选择显示表数据U可以查看您验证输入的详细信息。
Go to server explorer and right click on User Profile table and Select "Show Table Data" U can view the details you entered for verification.
步骤6
•现在让我们实现了密码重置功能转到帐户控制并创建下列控制器的操作方法(GET)
Step 6• Now lets implement the password reset functionality Go to account controller and create the following controller action method (GET )
[AllowAnonymous]
public ActionResult ForgotPassword()
{
return View();
}
• (POST)
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ForgotPassword(string UserName)
{
//check user existance
var user = Membership.GetUser(UserName);
if (user == null)
{
TempData["Message"] = "User Not exist.";
}
else
{
//generate password token
var token = WebSecurity.GeneratePasswordResetToken(UserName);
//create url with above token
var resetLink = "<a href='" + Url.Action("ResetPassword", "Account", new { un = UserName, rt = token }, "http") + "'>Reset Password</a>";
//get user emailid
UsersContext db = new UsersContext();
var emailid = (from i in db.UserProfiles
where i.UserName == UserName
select i.EmailId).FirstOrDefault();
//send mail
string subject = "Password Reset Token";
string body = "<b>Please find the Password Reset Token</b><br/>" + resetLink; //edit it
try
{
SendEMail(emailid, subject, body);
TempData["Message"] = "Mail Sent.";
}
catch (Exception ex)
{
TempData["Message"] = "Error occured while sending email." + ex.Message;
}
//only for testing
TempData["Message"] = resetLink;
}
return View();
}
•获取控制器的动作仅返回视图。
•在POST控制器操作:
获取的用户名
验证它的存在
生成密码重置令牌
建立网址通过电子邮件发送。
• The GET controller action just returns the view.• The POST controller action :Receives the usernameVerifies its existenceGenerates Password reset tokenBuilds URL to be emailed.
步骤7
•右键点击忘记密码的操作方法,并添加视图的code为视图页面将如下
Step 7• Right click on the forgot password action method and add view The code for the view page will be as below
@{
ViewBag.Title = "Forgot Password";
}
<h2>Forgot Password</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<fieldset>
<legend>Forgot Password Form</legend>
<ol>
<li>
@Html.Label("User Name", new { @for = "UserName" })
@Html.TextBox("UserName")
<span style="color:red;">@TempData["Message"]</span>
</li>
</ol>
<input type="submit" value="Recover" />
</fieldset>
}
•视图页面将显示一个文本框,其中用户可以输入用户名。
• The view page will display a textbox where in user can enter the user name.
步骤8
•现在去Solution Explorer中... ...型号Account模型...用户资料查看模型。变化已经凸显
Step 8• Now go to Solution Explorer...Models ... Account model … User Profile View Model. Changes have been highlighted
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
//new properties
public string EmailId { get; set; }
public string Details { get; set; }
}
步骤9
•现在去Solution Explorer中...查看...帐户...登录查看。
现在,我们可以看到一个选项的情况下,他已经忘了他的恢复密码。
Step 9• Now go to Solution Explorer...Views ... Account … Login View.Now we can see an option to recover his password in case he has forgotten it.
<ul>
<li>
@Html.ActionLink("Register", "Register") if you don't have an account.
</li>
<li>
@Html.ActionLink("Forgot Password", "ForgotPassword") if you want to recover your password.
</li>
</ul>
第2部分
接收密码的URL复位信息
Part 2 Receiving Password Reset Information from URL
第1步
•转到解决方案资源管理器... ...帐户控制...
创建新重置密码操作方法
•这种方法正在接受'联合国'(这是用户名)和RT(即重置密码令牌)从URL。
Step 1• Go to Solution Explorer...Controller ... Account Controller …Create new Reset Password Action Method• This method is accepting ‘un’ (which is username) and ‘rt’ (which is password reset token) from the URL.
[AllowAnonymous]
public ActionResult ResetPassword(string un, string rt)
{
UsersContext db = new UsersContext();
//TODO: Check the un and rt matching and then perform following
//get userid of received username
var userid = (from i in db.UserProfiles
where i.UserName == un
select i.UserId).FirstOrDefault();
//check userid and token matches
bool any = (from j in db.webpages_Memberships
where (j.UserId == userid)
&& (j.PasswordVerificationToken == rt)
//&& (j.PasswordVerificationTokenExpirationDate < DateTime.Now)
select j).Any();
if (any == true)
{
//generate random password
string newpassword = GenerateRandomPassword(6);
//reset password
bool response = WebSecurity.ResetPassword(rt, newpassword);
if (response == true)
{
//get user emailid to send password
var emailid = (from i in db.UserProfiles
where i.UserName == un
select i.EmailId).FirstOrDefault();
//send email
string subject = "New Password";
string body = "<b>Please find the New Password</b><br/>" + newpassword; //edit it
try
{
SendEMail(emailid, subject, body);
TempData["Message"] = "Mail Sent.";
}
catch (Exception ex)
{
TempData["Message"] = "Error occured while sending email." + ex.Message;
}
//display message
TempData["Message"] = "Success! Check email we sent. Your New Password Is " + newpassword;
}
else
{
TempData["Message"] = "Hey, avoid random request on this page.";
}
}
else
{
TempData["Message"] = "Username and token not maching.";
}
return View();
}
步骤2
•右键单击重置密码的操作方法,并添加视图的code为视图页面将如下
Step 2• Right click on the reset password action method and add view The code for the view page will be as below
@{
ViewBag.Title = "ResetPassword";
}
<h2>Password Mailed :) </h2>
步骤3
•转到解决方案资源管理... ...型号型号帐户...
做以下修改。
•我们创建用户配置DB模式的一个实例,并实现db.webpages_Memberships'作为DbSet.Usewebpages_Memberships的一种模式。
Step 3• Go to Solution Explorer...Models... Account Models …Make the following changes.• We create an instance of UserProfile DB Model and implement db.webpages_Memberships’ as DbSet.Use ‘webpages_Memberships’ as a model.
public class UsersContext : DbContext
{
public UsersContext()
: base("DefaultConnection")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
public DbSet<webpages_Membership> webpages_Memberships { get; set; }
}
[Table("webpages_Membership")]
public class webpages_Membership
{
[Key]
public int UserId { get; set; }
public DateTime CreateDate { get; set; }
public string ConfirmationToken { get; set; }
public bool IsConfirmed { get; set; }
public DateTime LastPasswordFailureDate { get; set; }
public int PasswordFailuresSinceLastSuccess { get; set; }
public string Password { get; set; }
public DateTime PasswordChangeDate { get; set; }
public string PasswordSalt { get; set; }
public string PasswordVerificationToken { get; set; }
public DateTime PasswordVerificationTokenExpirationDate { get; set; }
}
步骤4
•随机密码生成功能添加到帐户控制
•呼吁将为用户生成一个随机密码时,此方法
Step 4• Add the Random Password Generation Function to the account controller• This method when called will generate a random password for the user
private string GenerateRandomPassword(int length)
{
string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@$?_-*&#+";
char[] chars = new char[length];
Random rd = new Random();
for (int i = 0; i < length; i++)
{
chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
}
return new string(chars);
}
第5步
•添加了发送电子邮件功能的账户控制器。
•此功能将首先发送邮件给用户,当用户点击恢复按钮忘记密码的形式。第一个邮件包含重置密码链接。当用户点击链接。用户会被重定向到重置密码页面。再次输入新密码将邮寄给用户。
•您需要把您的电子邮件地址的地方[email protected]的,写你的密码。
Step 5• Add the Send Email Function in account controller.• This function will send first mail to user when user clicks on recover button on forgot password form. The first mail contains the reset password link. When user clicks on the link. User will be redirected to the reset password page. Again the new password will be mailed to the user.• You need to put in your email address in place of [email protected] and write your password.
private void SendEMail(string emailid, string subject, string body)
{
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
client.EnableSsl = true;
client.Host = "smtp.gmail.com";
client.Port = 587;
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("[email protected]", "password");
client.UseDefaultCredentials = false;
client.Credentials = credentials;
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.From = new MailAddress("[email protected]");
msg.To.Add(new MailAddress(emailid));
msg.Subject = subject;
msg.IsBodyHtml = true;
msg.Body = body;
client.Send(msg);
}
这篇关于忘记密码+电子邮件确认在ASP.NET MVC WebMatrix中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!