4

クッキーを段階的に作成するにはどうすればよいですか。

ユーザーが [Remember Me?] をクリックしたときにユーザーのログイン ID とパスワードを保存しますか? オプション

そして、私は一定時間後にこのクッキーを殺すつもりです

4

1 に答える 1

14

Cookie は、単純な古い ASP.NET と同じ方法で作成されますResponse。.

        public ActionResult Login(string username, string password, bool rememberMe)
        {
            // validate username/password

            if (rememberMe)
            {
               HttpCookie cookie = new HttpCookie("RememberUsername", username);
               Response.Cookies.Add(cookie);
            }

            return View();

        }

ただし、Forms Auth を使用している場合は、FormsAuth チケット Cookie を永続的にすることができます。

        public ActionResult Login(string username, string password, bool rememberMe)
        {
            // validate username/password

            FormsAuthentication.SetAuthCookie(username, rememberMe);

            return View();

        }

次のように Cookie を読み取ることができます。

public ActionResult Index()
{
    var cookie = Request.Cookies["RememberUsername"];

    var username = cookie == null ? string.Empty : cookie.Value; // if the cookie is not present, 'cookie' will be null. I set the 'username' variable to an empty string if its missing; otherwise i use the cookie value

    // do what you wish with the cookie value

    return View();
}

フォーム認証を使用していて、ユーザーがログインしている場合、次のようにユーザー名にアクセスできます。

public ActionResult Index()
{


    var username = User.Identity.IsAuthenticated ? User.Identity.Name : string.Empty;

    // do what you wish with user name

    return View();
}

チケットの内容を解読して読み取ることができます。必要に応じて、少量のカスタム データをチケットに保存することもできます。詳細については、この記事を参照してください。

于 2012-05-14T09:29:17.857 に答える