C# Simplemembership和cookie用户数据兼容性

C# Simplemembership和cookie用户数据兼容性,c#,asp.net-mvc,asp.net-mvc-4,simplemembership,httpcookie,C#,Asp.net Mvc,Asp.net Mvc 4,Simplemembership,Httpcookie,我正在尝试使用SimpleMembershipProvider进行表单验证。现在,该提供程序在内部创建一个FormsAuth cookie,而不需要任何额外的用户数据 我想在cookie中包含一些其他信息,如用户ID、角色等 我已经实现了以下功能- 但是,在MyAuthorizeAttribute中,它从不在cookie中获取用户数据。上面的代码有什么错误吗?或者在其他地方遗漏了什么?找到了这个问题的答案 查看链接 您的cookie名称是否与FormsAuthentication.FormsS

我正在尝试使用SimpleMembershipProvider进行表单验证。现在,该提供程序在内部创建一个FormsAuth cookie,而不需要任何额外的用户数据

我想在cookie中包含一些其他信息,如用户ID、角色等

我已经实现了以下功能-



但是,在MyAuthorizeAttribute中,它从不在cookie中获取用户数据。上面的代码有什么错误吗?或者在其他地方遗漏了什么?

找到了这个问题的答案

查看链接


您的cookie名称是否与
FormsAuthentication.FormsScookeName
相同。此外,请在authorize类中放置一个断点,并检查请求中可用的cookie。能否显示完整的登录代码(而不仅仅是cookie部分)?您的cookie可能在某个时刻被默认cookie覆盖。
public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (isAuthorized)
        {
            var formsCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
            var identity = new AppUserIdentity(string.Empty, true);
            if (formsCookie != null)
            {
                var cookieValue = FormsAuthentication.Decrypt(formsCookie.Value);
                if (cookieValue != null && !string.IsNullOrEmpty(cookieValue.UserData))
                {
                    var cookieData = SerializerXml.Deserialize<UserNonSensitiveData>(cookieValue.UserData);
                    identity = new AppUserIdentity(cookieValue.Name, cookieData.UserId, true);
                }
                else if (cookieValue != null)
                {
                    //TODO: Find out technique to get userid value here
                    identity = new AppUserIdentity(cookieValue.Name, null, true);
                }
            }

            var principal = new AppUserPrincipal(identity);
            httpContext.User = Thread.CurrentPrincipal = principal;
        }
        return isAuthorized;
    }
}
var newticket = new FormsAuthenticationTicket(ticket.Version,
                                                      ticket.Name,
                                                      ticket.IssueDate,
                                                      ticket.Expiration,
                                                      ticket.IsPersistent,
                                                      userdata,
                                                      ticket.CookiePath);

        // Encrypt the ticket and store it in the cookie
        cookie.Value = FormsAuthentication.Encrypt(newticket);
        cookie.Expires = newticket.Expiration.AddHours(24);

        Response.Cookies.Set(cookie);