Search code examples
asp.netajaxjsonwcfwcf-binding

Can I use JSON in a WCF Service that uses wsHttpBinding?


I need to use wsHttpBinding binding because my service needs access to HttpContext.Current.Session. I understand from my research that this is not possible with webHttpBinding. However all of my ajax is written to use JSON and I would like it very much if I didn't have to rewrite all of it.

My service works perfectly with webHttpBinding until I need to use the session.

Or, is there a way to get webHttpBinding access to the session?

EDIT:

  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
    <behaviors>
      <endpointBehaviors>
        <behavior name="LiteBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="LiteBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service behaviorConfiguration="LiteBehavior" name="Lite.CMS.Services.LiteService">
        <endpoint behaviorConfiguration="LiteBehavior" address="" binding="webHttpBinding" contract="Lite.CMS.Services.Interfaces.ILiteService" />
      </service>
    </services>
  </system.serviceModel>

And my contract:

[ServiceContract (SessionMode=SessionMode.Allowed)]
public interface ILiteService
{
    [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
    [OperationContract]
    void Item_Save(string Name);
}

And Implementation:

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class LiteService : ILiteService
{
    public void Item_Save(string Name)
    {
        // I can't get access to HttpContext.Current.Session variables here.
    }
}

Solution

  • webHttpbinding is a stateless binding, it doesn't use SOAP.
    If you try to put SessionMode=SessionMode.Required it will throw an error on service start.
    If you want to implement session on a stateless protocol, you'll need to do it by hand with cookies.

    See :

    http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/fe2a2ce9-ba97-4784-95f8-bdce5ffcd8eb/
    How to Manage Sessions in Restful WCF Service
    REST WCF service and Session‏ in ASP.NET