我想在asp.net中扩展IPrincipal,以便获得我将要定义的用户类型。我想在控制器中实现这一点。
string type = User.UserType 然后在我的扩展方法中,我将有一个类似这样的方法
public string UserType()
{
// do some database access
return userType
}我该怎么做呢?有可能吗?谢谢!
发布于 2010-07-10 00:24:22
您可以创建一个扩展方法:
public static string UserType(this IPrincipal principal) {
// do some database access
return something;
}发布于 2010-07-10 00:22:41
好的。让你的类实现IPrincipal:
public class MyPrinciple : IPrincipal {
// do whatever
}扩展方法:
public static string UserType(this MyPrinciple principle) {
// do something
}发布于 2010-07-10 00:22:24
下面是一个实现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;
}
}
}享受吧!
https://stackoverflow.com/questions/3214520
复制相似问题