我想在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