2010-07-09 54 views
7

我想在asp.net中扩展IPrincipal,让我得到我将定义的usertype。我想有可能在控制器asp.net的延伸IPrincipal

string type = User.UserType 

然后在我的扩展方法,我将有一个像

public string UserType() 
{ 
    // do some database access 
    return userType 

} 

我怎么能做到这一点的方法做到这一点?可能吗? 谢谢!

+0

你不扩展接口,你实现它。 – 2010-07-09 16:20:38

+0

或者,可以扩展它,但这是别的。这将创建一个新的界面,这是一个基地的超集。 – 2010-07-09 16:21:02

回答

10

您可以扩展方法:

public static string UserType(this IPrincipal principal) { 
    // do some database access 
    return something; 
} 
+0

这会很聪明,但风险很大。 “返回某些东西”部分实际上不得不将其下达到他的实现并呼叫某个财产。如果在任何其他IPrincpal实现上执行,这将会失败。 – 2010-07-09 16:25:40

+0

该类需要看起来像在哪个扩展方法找到? – twal 2010-07-09 16:26:25

+1

它需要是一个'静态类'。 – SLaks 2010-07-09 16:27:19

2

这是一个实现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!

+0

正确,除了它们无法调用UserType给定对IPrincipal的引用。 – 2010-07-09 16:26:25

2

基本上没有。您可以实现IPrincipal,其类别为MyPrincipal,并且该类可以具有UserType属性,但您必须通过自己类型的引用访问该实例才能访问该实例,而不是通过接口引用。

编辑

扩展方法可以工作,但前提是你是绝对肯定你永远不会把它的东西,实现了IPrincipal但不是你自己的类的实例。

+0

谢谢。我会考虑IPrincipal在其他地方实施的可能性。我不确定它是否会应用于我的应用程序。我不确定哪些情况会导致这种情况。但如果是这样的话,这对我来说也是有用的。谢谢你,先生! – twal 2010-07-09 16:33:42

+0

@twal:通常,框架会给你一个IPrincipal,它的实现是来自该框架的一些类。只要你确定这不会发生,一个扩展方法将满足你的需求。 – 2010-07-09 16:45:01

+0

谢谢史蒂文! – twal 2010-07-09 21:06:57

3

当然。让你的类实现的IPrincipal:

public class MyPrinciple : IPrincipal { 
    // do whatever 
} 

扩展方法:

public static string UserType(this MyPrinciple principle) { 
    // do something 
} 
+0

与SLaks的答案相同的问题:“做某事”将涉及向下转播,这可能会失败。 – 2010-07-09 16:27:18