asp.netでIPrincipalを拡張して、定義するユーザータイプを取得できるようにします。コントローラでこれを可能にしたいと思います
string type = User.UserType
次に、私の拡張メソッドでは、次のようなメソッドがあります
public string UserType()
{
// do some database access
return userType
}
これどうやってするの?出来ますか?ありがとう!
asp.netでIPrincipalを拡張して、定義するユーザータイプを取得できるようにします。コントローラでこれを可能にしたいと思います
string type = User.UserType
次に、私の拡張メソッドでは、次のようなメソッドがあります
public string UserType()
{
// do some database access
return userType
}
これどうやってするの?出来ますか?ありがとう!
拡張メソッドを作成できます。
public static string UserType(this IPrincipal principal) {
// do some database access
return something;
}
もちろん。クラスにIPrincipalを実装させます。
public class MyPrinciple : IPrincipal {
// do whatever
}
拡張方法:
public static string UserType(this MyPrinciple principle) {
// do something
}
IPrincipalを実装するカスタムクラスの例を次に示します。このクラスには、ロールの所属を確認するための追加のメソッドがいくつか含まれていますが、要件に応じてUserTypeという名前のプロパティが表示されます。
public class UserPrincipal : IPrincipal
{
private IIdentity _identity;
private string[] _roles;
private string _usertype = string.Empty;
public UserPrincipal(IIdentity identity, string[] roles)
{
_identity = identity;
_roles = new string[roles.Length];
roles.CopyTo(_roles, 0);
Array.Sort(_roles);
}
public IIdentity Identity
{
get
{
return _identity;
}
}
public bool IsInRole(string role)
{
return Array.BinarySearch(_roles, role) >= 0 ? true : false;
}
public bool IsInAllRoles(params string[] roles)
{
foreach (string searchrole in roles)
{
if (Array.BinarySearch(_roles, searchrole) < 0)
{
return false;
}
}
return true;
}
public bool IsInAnyRoles(params string[] roles)
{
foreach (string searchrole in roles)
{
if (Array.BinarySearch(_roles, searchrole) > 0)
{
return true;
}
}
return false;
}
public string UserType
{
get
{
return _usertype;
}
set
{
_usertype = value;
}
}
}
楽しみ!
基本的にはありません。IPrincipal
などのクラスを使用して実装できMyPrincipal
、そのクラスはUserType
プロパティを持つことができますが、インスタンスに到達するには、インターフェイス参照ではなく、独自のタイプの参照を介してインスタンスにアクセスする必要があります。
編集
IPrincipal
拡張メソッドは機能する可能性がありますが、それを実装しているが独自のクラスのインスタンスではないもので呼び出すことは絶対にないと確信している場合に限ります。