Asp.net Extending IPrincipal

I would like to extend the IPrincipal in asp.net to allow me to get a custom type that I will define. I would like to do this in the controller

string type = User.UserType 

then in my extension method I will have a method like

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

How can i do this? Is it possible? Thanks!

+7
inheritance c # interface iprincipal
source share
4 answers

You can make an extension method:

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

Of course. Make your class implement IPrincipal:

 public class MyPrinciple : IPrincipal { // do whatever } 

Extension Method:

 public static string UserType(this MyPrinciple principle) { // do something } 
+3
source share

Here is an example of a custom class that implements IPrincipal. This class includes several additional methods for checking role ownership, but displays a property called UserType to suit your requirements.

  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 it!

+2
source share

In principle, no. You can implement IPrincipal with a class such as MyPrincipal , and this class can have a UserType property, but you will need to access the instance through a link of its own type in order to reach it, and not through a link to the interface.

change

The extension method may work, but only if you are absolutely sure that you will never call it something that implements IPrincipal , but is not an instance of your own class.

+2
source share

All Articles