WCF and ASP.NET Compatibility Mode

Recently I had a troublesome error when developing a web hosted WCF service. The solution relied on some legacy components from an ASP.NET website - that is some cases throw errors, seemingly at random.

After alot of trouble shooting I noticed that the problem only occured when - after building the project - I made the first request through a WCF client. The legacy components would then return errors until the project had been rebuilt. If I after rebuilding made a request to a test page within the WCF-project, the legacy components worked like a charm.

Although I've done my fair share of web services in the past, this was my first WCF project. And there's a major difference between standard ASP.NET webservices and WCF.

By default calls to the WCF service is run outside of the ASP.NET pipeline, in something called "Mixed Transports Mode". That means that it will bypass the ASP.NET pipeline and you'll loose things like HttpContext. Some of which the legacy components in my project apparently required.

The solution was to switch to "ASP.NET Compability Mode". That means that the WCF request is treated as any other ASP.NET request.

This is done by setting aspNetCompatibilityEnabled to true in the web.config:
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
...

And also decorate the WCF service class with the AspNetCompatibilityRequirements attribute:
[ServiceBehavior]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]

public class UserService : IUserService {
...

To learn more about this I recommend the following post about ASP.NET Compability Mode.

Related posts:

Comments

comments powered by Disqus