2

I currently maintain a legacy application and I'm trying hard to make it more testable as I release new features to it. The application is hosted on IIS and is a WCF rest service on .net 4.5 that exposes several different service operations. In my attempt to make things better I ran into the problem of fetching Username from the context.

I really didn't know that there were so many different contexts that is available in an application especially when all you really wanted from it is the Username or maybe just fake some headers. The three that I'm currently aware of are:

All the three of them have wonderful documentation on MSDN which is why I posted the corresponding links in the bullets above. So by just directing me to the documentation isn't any more useful than what I've searched so far.

My question/questions are kind of related so I'm compiling it as one.

I learned the real difference between WebOperationContext and HttpContext from this simple answer here at https://stackoverflow.com/a/18777835/2262959 (although he didn't state where he got that information from, I believe it is hidden somewhere in msdn or from personal experience).

  1. How are the two aforementioned contexts related to OperationContext, guessing from the name, I kind of feel, I can get hold of either of the other two using this one, or maybe not.
  2. Can I always rely on OperationContext to fetch the current username or to get (or even fake) the HttpRequest Headers? Or would I always have to rely on a specific one to retrieve user information?
  3. If my purpose is to fake one context to achieve what I want, which is the one that I should fake? (I use FakeItEasy in my project)

Currently my code does something like this:

if (OperationContext.Current != null && OperationContext.Current.ServiceSecurityContext != null)
  return OperationContext.Current.ServiceSecurityContext.WindowsIdentity;
if (HttpContext.Current == null) return WindowsIdentity.GetCurrent();
if (HttpContext.Current.User != null)
{
  return HttpContext.Current.User.Identity as WindowsIdentity;
}
return WindowsIdentity.GetCurrent();

I hope that piece of code makes it clear why I'm so confused. I really don't know what to rely on to fetch the current user identity, from the source repository change description, someone has mentioned that HttpContext.Current didn't always fetch the right user, so have to check OperationContext. When and why does that even happen? I don't know.

I'd be happy to even read it from a book, but I really don't know what to rely on.

0 Answers0