我可以在使用wsHttpBinding的WCF服务中使用JSON吗?

时间:2012-08-01 12:46:07

标签: asp.net ajax json wcf wcf-binding

我需要使用wsHttpBinding绑定,因为我的服务需要访问HttpContext.Current.Session。我从研究中了解到,webHttpBinding无法做到这一点。但是我的所有ajax都是使用JSON编写的,如果我不需要重写它,我会非常喜欢它。

我的服务与webHttpBinding完美配合,直到我需要使用会话。

或者,有没有办法让webHttpBinding访问会话?

修改

  <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>

我的合同:

[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);
}

实施:

[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.
    }
}

1 个答案:

答案 0 :(得分:0)

webHttpbinding是无状态绑定,它不使用SOAP 如果您尝试放置SessionMode = SessionMode.Required,它将在服务启动时抛出错误 如果要在无状态协议上实现会话,则需要手动使用cookie。

见:

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