John S
John S

Reputation: 8351

Determining what user context a calling application is.

I have a reusable data access component that is being used in Winform apps and Web apps. Part of the module needs to log the user that is making any changes to the data. i.e. CreatedBy or ModifiedBy

If the component was being used strictly for Winform access I could use WindowsIdentity.GetCurrent().Name to get the current user's name and if the component was being used only in web apps I could use HttpContext to get the use name.

What I would like to do is make the component flexible enough that it can be used in both situations. So how do I detect what type of app is calling the component so that I can examine the resulting context for the user name?

Upvotes: 0

Views: 601

Answers (1)

John Wu
John Wu

Reputation: 52290

You can always check to see if HttpContext even exists. If it doesn't (HttpContext.Current = null), you're not running a web application.

var httpContext = HttpContext.Current;
var userName = (httpContext == null) 
             ? WindowsIdentity.GetCurrent().Name 
             : httpContext.User.Identity.Name;

Another approach is just to use the current thread's principal, if you are setting it (you should be):

var principal = System.Threading.Thead.CurrentPrincipal;
var userName = principal.Identity.Name;

Upvotes: 1

Related Questions