In this article I will explain how to access and use HttpContext.Current in WCF Service in ASP.Net using C# and VB.Net.
When HttpContext.Current is used in a WCF Service in ASP.Net, the value of HttpContext.Current is always NULL.
 
 
The Problem
When HttpContext.Current is used in a WCF Service in ASP.Net, the value of HttpContext.Current is always NULL.
Access and Use HttpContext.Current in WCF Service in ASP.Net
 
 
The Solution
The solution is to make the WCF Service work in ASP.Net compatibility mode. In order to make the WCF Server work in ASP.Net compatibility mode, you need to follow the steps shown below.
1. Set aspNetCompatibilityEnabled attribute to true for the serviceHostingEnvironment tag in system.serviceModel section of the Web.Config file.
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
 
2. Import the following namespaces in the WCF Service class.
C#
using System.Web;
using System.ServiceModel.Activation;
 
VB.Net
Imports System.Web
Imports System.ServiceModel.Activation
 
3. Decorate the WCF Service class with the AspNetCompatibilityRequirements attribute.
C#
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class Service : IService
{
    public string GetName()
    {
        return HttpContext.Current.User.Identity.Name;
    }
}
 
VB.Net
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Required)> _
Public Class Service
    Implements IService
    Public Function GetName() As String Implements IService.GetName
        Return HttpContext.Current.User.Identity.Name
    End Function
End Class
 
Access and Use HttpContext.Current in WCF Service in ASP.Net
 
 
Downloads