HttpContextBaseから役割の配列を取得する方法はありますか?
私はそのようなクラスをやりたいと思っています:
public static IList<string> GetUserRoles(this HttpContextBase context)
{
if (context != null)
{
}
// return roles array;
}
助けてくれてありがとう。
HttpContextBaseから役割の配列を取得する方法はありますか?
私はそのようなクラスをやりたいと思っています:
public static IList<string> GetUserRoles(this HttpContextBase context)
{
if (context != null)
{
}
// return roles array;
}
助けてくれてありがとう。
次を使用できます。
System.Web.Security.Roles.GetAllRoles()
HttpContextBaseを使用する理由は何ですか?
*編集* おっと、特定のユーザーの役割のリストが必要だと思います。利用可能なすべての役割のリストが必要だと思いました。
ロールをループして、どのロールが適用されるかを確認できます。
HttpContextBase.User.IsInRole(role);
おそらく、Application_AuthenticateRequestでGenericPrincipalを使用しています。一連のロールを公開するカスタムプリンシパルを作成することをお勧めします。
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;
}