views:

38

answers:

2

Hi I have implemented NHibernate custom context (ICurrentSessionContext). In this context I inject the NHibernate session so I have Session per call pattern setup. Ok, now I have made an interceptor that takes userId of the current logged user. Now I do this:

public ISession CurrentSession()
{
  // Get the WCF InstanceContext:
  var contextManager = OperationContext.Current.InstanceContext.Extensions.Find<NHibernateContextManager>();
  if (contextManager == null)
  {
    throw new InvalidOperationException(
      @"There is no context manager available.
      Check whether the NHibernateContextManager is added as InstanceContext extension.
      Make sure the service is being created with the NhServiceHostFactory.
      This Session Provider is intended only for WCF services.");
   }

   var session = contextManager.Session;
   AuditLogInterceptor interceptor = new AuditLogInterceptor();
   if (session == null)
   {
     session = this._factory.OpenSession(interceptor);
     interceptor.Session = session;

     contextManager.Session = session;
   }

   return contextManager.Session;
}

My AuditLogInterceptor takes UserId but I don't know how (from where) to get this userId. Please help.

A: 

I assume that the current user is being set as the principal on the current thread?

If so, something like this is what you need:

var userName = Thread.CurrentPrincipal.Identity.Name;

There is some additional information in this article that may prove helpful.

DanP
A: 

If your user is authenticated you can use: OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.Name

Best regards, Ladislav

Ladislav Mrnka