8

ASP.Net MVC 4 サイトの SimpleMembership を把握しようとしています。UserProfile をカスタム プロパティ AccountTypeId で拡張しました。拡張プロパティを使用してデータベース テーブルを更新し、登録時にデータベースにデータを保存できます。ログイン後にユーザーに関するデータを取得する方法について少し混乱しています。

私の Account コントローラーには、ユーザーがログインしたときに投稿される Login アクションがあります。私のコードは次のとおりです。

[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel model, string returnUrl)
    {
        if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
        {
            var userName = WebSecurity.CurrentUserName;
            var identityName = User.Identity.Name;
            var currentuserid = WebSecurity.GetUserId(model.UserName);
            var context = new UsersContext();
            var user = context.UserProfiles.SingleOrDefault(u => u.UserId == currentuserid);
            var accountTypeId = user.AccountTypeId;

            return RedirectToLocal(returnUrl);
        }

        // If we got this far, something failed, redisplay form
        ModelState.AddModelError("", "The user name or password provided is incorrect.");
        return View(model);
    }

WebSecurity.CurrentUserName と User.Identity.Name はどちらも空の文字列ですが、WebSecurity.GetUserId(model.UserName) を使用して UserId を取得できるため、ユーザー データを取得でき、accountTypeId を取得できます。

奇妙なのは、ユーザーがランディング ページにリダイレクトされた後、.cshtml ページから呼び出されると、User.Identity.Name がページに表示されることです。したがって、コントローラーの Login アクションと宛先ページの間のどこかで、 User.Identity にデータが設定されます。

WebSecurity.Login チェックを通過したので、WebSecurity はログインしているユーザーに関する情報を持っていると思いますが、そうではないようです。

私は何が欠けていますか?

4

1 に答える 1

9

ユーザー名は Cookie に書き込まれます。Cookie データを利用できるようにするには、それを Response に配置し、ブラウザに送り返す必要があります。次のリクエストで、Cookie の値が読み取られ、User.Identity.Nameプロパティの設定に使用されます。

つまり、Redirect 呼び出しの後まで、User.Identity.Nameプロパティは空の文字列である必要があります。サインオン後のリダイレクトの目的は、Cookie をブラウザーに書き込み、後続の要求でユーザーがサインオンしたものとして扱われるようにすることです。

于 2012-09-29T15:17:55.803 に答える