Extending CurrentPrincipal

If you are wanting to use the built in ASP Identity but you are also wanting to store extra data against that user whilst they use the website then you can extend the CurrentPrincipal easily.

So in this case I’m going to use it in the sense of it being for a company called Company, here’s my extended code:


public class CompanyPrincipal : IPrincipal
{
private _Company_Employee_Access employeeAccess = new _Company_Employee_Access();
public _Company_Employee_Detail Information { get; set; }
public IIdentity Identity { get; private set; }
public CompanyPrincipal(IIdentity identity)
{
Information = employeeAccess.getEmployeeByName(identity.Name);
this.Identity = identity;
}
public bool IsInRole(string role)
{
throw new NotImplementedException();
}
}

So the extra information we want to store is an instance of: _Company_Employee_Detail called Information.

We fill it using employeeAccess.getEmployeeByName(identity.Name); so that would be your code to return _Company_Employee_Detail with the correct information.

In MVC you can then access it like so:

@{
ViewBag.Title = "Home Page";
var User = (CompanyPrincipal)Context.User;
}

Sup @User.Information.FirstName ?

 

Leave a Reply

Your email address will not be published. Required fields are marked *