我想在asp.net中擴展IPrincipal,讓我得到我將定義的usertype。我想有可能在控制器asp.net的延伸IPrincipal
string type = User.UserType
然後在我的擴展方法,我將有一個像
public string UserType()
{
// do some database access
return userType
}
我怎麼能做到這一點的方法做到這一點?可能嗎? 謝謝!
我想在asp.net中擴展IPrincipal,讓我得到我將定義的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的示例自定義類。該類包含一些額外的方法來檢查角色從屬關係,但會顯示一個名爲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;
}
}
}
Enjoy!
正確,除了它們無法調用UserType給定對IPrincipal的引用。 – 2010-07-09 16:26:25
基本上沒有。您可以實現IPrincipal
,其類別爲MyPrincipal
,並且該類可以具有UserType
屬性,但您必須通過自己類型的引用訪問該實例才能訪問該實例,而不是通過接口引用。
編輯
擴展方法可以工作,但前提是你是絕對肯定你永遠不會把它的東西,實現了IPrincipal
但不是你自己的類的實例。
當然。讓你的類實現的IPrincipal:
public class MyPrinciple : IPrincipal {
// do whatever
}
擴展方法:
public static string UserType(this MyPrinciple principle) {
// do something
}
與SLaks的答案相同的問題:「做某事」將涉及向下轉播,這可能會失敗。 – 2010-07-09 16:27:18
你不擴展接口,你實現它。 – 2010-07-09 16:20:38
或者,可以擴展它,但這是別的。這將創建一個新的界面,這是一個基地的超集。 – 2010-07-09 16:21:02