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 ?

 

ASP.NET Session Timeout

During a redevelopment of my employers website we had massive issues with session timeout’s during use of the website during development, even a simple change to a page on the site was causing the application to recompile and then lose the session data.

This was due to the use of InProc (In Process Mode) Mode for the session, to fix this we moved to StateServer using the following setting in the web.config file:

<sessionState mode=”StateServer” stateConnectionString=”tcpip=127.0.0.1:42424″ cookieless=”UseCookies” timeout=”60″ regenerateExpiredSessionId=”true”/>
 

This now means that even if the application recompiles the session data will remain and will only be lost of the application is restarted or IIS is restarted. Hope this helps anyone searching about session timeouts in asp.net