3

これらの2つの機能には、WebMatrixコードに一連のヘルパー関数とスキーマが含まれているようです。ただし、それを実行するためのコントローラーメソッドまたはビューはないため、自分で実装する必要があります。

このコードをアプリにコピーできるサンプルはありますか?私は何かを探しています:

  • パスワードを忘れた場合の電子メールを生成する
  • 確認メールを生成する
  • パスワードビューを忘れた+コントローラー方式
  • 確認メールビューを再送+コントローラー方式
4

1 に答える 1

16

パスワードを忘れた場合の機能

先日、asp.net MVC 4 で「パスワードを忘れた場合の機能」を作成しようとしました。私はついに道を見つけました。15の簡単なステップ

パート 1 パスワードリセット情報を電子メールで送信する

ステップ 1 • Mvc 4 c# インターネット アプリケーション テンプレートを作成します :) (アカウントとホーム コントローラーが自動的に生成されます) • プロジェクトをビルドして実行します。登録してログインします。(単純なメンバーシップ テーブルが生成されます)

                        Everything working fine?

ステップ 2 • おっと!彼らは登録時に私たちの電子メールIDを尋ねません! パスワード トークンをユーザーに送信するには、メール ID が必要です!! それでは、データベースにいくつかの変更を加えて、サーバー エクスプローラーに移動しましょう。(見つからない場合は、Ctrl + alt + S を押してください) • 「データ接続」を展開すると、いくつかのテーブルが表示されます。ユーザー プロファイル テーブルを開きます。次の列を追加します。

  1. EmailId nvarchar(max) 2.Details nvarchar(max)

ステップ 3 • ソリューション エクスプローラー...モデル...アカウント モデル...モデルの登録に移動します。 • 電子メール ID と詳細の 2 つのプロパティを追加します。

//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…Views ... Account Views ... Register.cshtml ビューに移動します。 • ユーザーが電子メール ID やその他の詳細を入力できるように、これら 2 つのプロパティを追加します。

  • @Html.LabelFor(m => m.EmailId) @Html.TextBoxFor(m => m.EmailId)
  • @Html.LabelFor(m => m.Details) @Html.TextBoxFor(m => m.Details)
  • ステップ 5 • ソリューション エクスプローラー…コントローラー…アカウント コントローラー…レジスター コントローラー アクション メソッドのポスト バージョンに移動します。 • ユーザーがメール ID やその他の詳細を入力できるように、これらのプロパティを追加します。

    [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 やその他の詳細を入力できるようにします。

    サーバー エクスプローラーに移動し、ユーザー プロファイル テーブルを右クリックして、[テーブル データの表示] を選択します。入力した詳細を確認のために表示できます。

    ステップ 6 • パスワード リセット機能を実装します  アカウント コントローラーに移動し、次のコントローラー アクション メソッド (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();
    }
    

    • GET コントローラ アクションはビューを返すだけです。• POST コントローラー アクション: ユーザー名を受信する その存在を確認する パスワード リセット トークンを生成する 電子メールで送信する URL を作成する。

    ステップ 7 • パスワードを忘れた場合のアクション メソッドを右クリックし、ビューを追加します ビュー ページのコードは次のようになります。

    @{
        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>
    }
    

    • ビュー ページには、ユーザーがユーザー名を入力できるテキスト ボックスが表示されます。

    ステップ 8 • ソリューション エクスプローラー...モデル...アカウント モデル...ユーザー プロファイル ビュー モデルに移動します。変更点が強調表示されました

    [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...Views ... Account ... Login View に移動します。これで、パスワードを忘れた場合にパスワードを回復するオプションが表示されます。

    <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からパスワードリセット情報を受け取る

    ステップ 1 • Solution Explorer...Controller ... Account Controller ... Create new Password Reset Action Method • このメソッドは、URL から 'un' (ユーザー名) と 'rt' (パスワード リセット トークン) を受け取ります。 .

    [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 • パスワードのリセット アクション メソッドを右クリックし、ビューを追加します ビュー ページのコードは次のようになります。

    @{
        ViewBag.Title = "ResetPassword";
    }
    
    <h2>Password Mailed :) </h2>
    

    ステップ 3 • ソリューション エクスプローラー...モデル...アカウント モデル...に移動し、次の変更を行います。• UserProfile DB モデルのインスタンスを作成し、db.webpages_Memberships を DbSet として実装します。「webpages_Memberships」をモデルとして使用します。

    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 • ランダム パスワード生成関数をアカウント コントローラーに追加します • このメソッドが呼び出されると、ユーザーのランダム パスワードが生成されます

     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 • アカウント コントローラーにメール送信機能を追加します。• この機能は、ユーザーがパスワードを忘れたフォームで回復ボタンをクリックすると、最初のメールをユーザーに送信します。最初のメールには、パスワードのリセット リンクが含まれています。ユーザーがリンクをクリックしたとき。ユーザーはパスワードのリセット ページにリダイレクトされます。再度、新しいパスワードがユーザーにメールで送信されます。• XXXXX@gmail.com の代わりにメール アドレスを入力し、パスワードを記入する必要があります。

    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("xxxxx@gmail.com", "password");
                client.UseDefaultCredentials = false;
                client.Credentials = credentials;
    
                System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
                msg.From = new MailAddress("xxxxx@gmail.com");
                msg.To.Add(new MailAddress(emailid));
    
                msg.Subject = subject;
                msg.IsBodyHtml = true;
                msg.Body = body;
    
                client.Send(msg);
            }
    
    于 2013-06-07T13:52:32.867 に答える