I have a business logic layer and 2 applications which use this, a MVC UI and a Web API project.
One of the properties on my classes is CreatedBy and UpdatedBy, which should hold the userid.
public Nullable<System.DateTime> CreatedTS { get; set; }
public string CreatedBy { get; set; }
public Nullable<System.DateTime> UpdatedTS { get; set; }
public string UpdatedBy { get; set; }
Given there are multiple consumers of the BLL what is the best way to capture the userId?
A) - Set this within the BLL using Environment.UserName
?
B) - Ask the client to set it and use model data annotation to make this Required
C) - Ask the client to pass this into any Create or Update methods in the BLL.
If you're using FormsAuthentication in both MVC and WebApi, you can access properties User.Identity.Name
.
int userId = db.Users.Single(r=>r.Name == User.Identity.Name);
In WebApi it will be HttpContext.Current.User.Identity.Name
This approach is quite secure. If you store userId
on client-side, user will be able to modify it.
I would generally use Thread.CurrentPrincipal.Identity.Name
.
To do so, you must ensure that Thread.CurrentPrincipal
is set to a principal representing the current user. This is done in the UI tier, and will happen automagically if you:
Use a RoleProvider in an ASP.NET application.
Use a RoleProvider
in a WCF application by setting principalPermissionMode ="UseAspNetRoles".
Call AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
in a client application.