C# Can';t检查用户角色。User.IsInRole返回false

C# Can';t检查用户角色。User.IsInRole返回false,c#,asp.net,asp.net-mvc,entity-framework,authentication,C#,Asp.net,Asp.net Mvc,Entity Framework,Authentication,我正在尝试检查视图中的用户角色: @if (User.IsInRole("User")) 但是一直都是假的 User.Identity.IsAuthenticated User.Identity.Name 返回true和name 我的表单身份验证服务: public static void SignIn(string userName, string role, bool createPersistentCookie) { FormsAuthenticationTicket aut

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

@if (User.IsInRole("User"))
但是一直都是假的

User.Identity.IsAuthenticated
User.Identity.Name
返回true和name

我的表单身份验证服务:


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);
}

通过添加到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);
}

您没有显示如何/在何处设置角色。您只在userData中传递一个名为role on的内容,而不显示如何/在何处设置角色。您只能在userData中传递名为role的内容。