Получение ролей из HttpContextBase - PullRequest
1 голос
/ 25 февраля 2011

Есть ли способ получить массив ролей из HttpContextBase?

Я ищу такой класс:

    public static IList<string> GetUserRoles(this HttpContextBase context)
    {
        if (context != null)
        {

        }

        // return roles array;
    }

Спасибо за помощь.

Ответы [ 2 ]

3 голосов
/ 25 февраля 2011

Вы можете использовать:

System.Web.Security.Roles.GetAllRoles()

По какой причине вы хотите использовать HttpContextBase?

* РЕДАКТИРОВАТЬ * Ой, я вижу, теперь вы хотите список ролей для данного пользователя. Я думал, что вы хотели список всех доступных ролей.

Вы можете просмотреть роли и проверить, какие из них применимы:

HttpContextBase.User.IsInRole(role);
2 голосов
/ 25 февраля 2011

Возможно, вы используете GenericPrincipal в Application_AuthenticateRequest. Я хотел бы предложить вам создать собственный принципал, который предоставляет массив ролей:

public class CustomPrincipal: IPrincipal
{
    public CustomPrincipal(IIdentity identity, string[] roles)
    {
        this.Identity = identity;
        this.Roles = roles;
    }

    public IIdentity Identity
    {
        get;
        private set;
    }

    public string[] Roles
    {
        get;
        private set;
    }

    public bool IsInRole(string role)
    {
        return (Array.BinarySearch(this.Roles, role) >= 0 ? true : false);  
    }
} 

Теперь вы можете прочитать ваш файл cookie и создать собственный принципал.

    protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
        HttpCookie authCookie = Request.Cookies[My.Application.FORMS_COOKIE_NAME];
        if ((authCookie != null) && (authCookie.Value != null))
        {
            var identity = new GenericIdentity(authTicket.Name, "FormAuthentication");
            var principal = new CustomPrincipal(identity, Roles, Code);
            Context.User = principal;
        }
    }

и ваша функция будет выглядеть примерно так:

    public static IList<string> GetUserRoles(this HttpContextBase context)
    {
        if (context != null)
        {
            return(((CustomPrincipal)context.User).Roles);
        }

        return (null);
        // return roles array;
    }
...