无法检查用户角色。User.IsInRole 返回 false



我正在尝试检查视图中的用户角色:

@if (User.IsInRole("User"))

但得到所有的时间都是假的,虽然

User.Identity.IsAuthenticated
User.Identity.Name

返回 true 和名称。

我的表单身份验证服务:


public static void SignIn(string userName, string role, bool createPersistentCookie)
{
    FormsAuthenticationTicket authTicket = new
        FormsAuthenticationTicket(1,
                            userName,
                            DateTime.Now,
                            DateTime.Now.AddMinutes(30), 
                            createPersistentCookie,
                            role);
    string encTicket = FormsAuthentication.Encrypt(authTicket);
    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
    {
        Expires = authTicket.Expiration,
        Path = FormsAuthentication.FormsCookiePath
    };
    if (HttpContext.Current != null)
    {
        HttpContext.Current.Response.Cookies.Add(cookie);
    }
}

和呼叫

FormsAuthenticationService.SignIn(model.UserName, "User", true);

通过添加到 Global.asax 来修复:

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
    if (authCookie == null || authCookie.Value == "")
        return;
    FormsAuthenticationTicket authTicket;
    try
    {
        authTicket = FormsAuthentication.Decrypt(authCookie.Value);
    }
    catch
    {
        return;
    }
    string[] roles = authTicket.UserData.Split(';');
    if (Context.User != null)
        Context.User = new GenericPrincipal(Context.User.Identity, roles);
}

最新更新