access HttpContext.Current from WCF Web Service

MacGyver picture MacGyver · May 5, 2011 · Viewed 33.6k times · Source

I just started using WCF Services with ASP.NET AJAX. I instantiate my WCF service from Javascript and then pass string variables as arguments to my WCF Service method (with an OperationContract signature). I then return a .NET object (defined with a DataContract) which is bound to my custom Javascript class. I'm having trouble authenticating based on the user logged into my web session. However, the WCF web service is a completely different service with no context to the HttpContext.Current object. What is the most secure way to get access to that object?

Answer

mthierba picture mthierba · May 5, 2011

You can get access to HttpContext.Current by enabling AspNetCompatibility, preferably via configuration:

<configuration>
  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
  </system.serviceModel>
</configuration>

That in turn allows you to get access to the current user: HttpContext.Current.User - which is what you're after, right?

You can even enforce AspNetCompatibility by decorating your service class with an additional attribute:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]

(In the System.ServiceModel.Activation namespace.) If that attribute is in place, your service will fail to start unless AspNetCompatibility is enabled!