【问题标题】:Can I use JSON in a WCF Service that uses wsHttpBinding?我可以在使用 wsHttpBinding 的 WCF 服务中使用 JSON 吗?
【发布时间】:2012-07-30 08:51:36
【问题描述】:

我需要使用 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.
    }
}

【问题讨论】:

  • 我有一个使用 webHttpBinding 实现的 WCF 服务,并且可以毫无问题地访问 HttpContext.Current.Session。您发现了什么问题?
  • 我所有的会话变量都是空的。我在页面加载中设置它们,然后当我调用我的服务时它们为空。
  • 您是否在服务合同中添加了 aspnetCompatibilityMode 属性并在配置中设置了兼容模式以支持会话
  • 是的,&lt;serviceHostingEnvironment aspNetCompatibilityEnabled="true" /&gt; 在我的 web.config 中,[ServiceContract (SessionMode=SessionMode.Allowed)] 在我的合同中。

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


【解决方案1】:

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

【讨论】:

  • 这两样东西我都准备好了。我可以访问HttpContext.Current.Session,但以前存储在其中的任何变量都不存在。就好像这是一个不同的会话。
  • 好的,我刚刚确认了 - HttpContext.Current.Session.SessionID 在我的页面加载到我的服务调用时是不同的。
  • webHttpbinding 是一个无状态会话,它不使用 SOAP。如果您尝试输入SessionMode=SessionMode.Required,它将在服务启动时引发错误。如果您想在无状态协议上实现会话,则需要使用 cookie 手动完成。
  • 我不想这样做,我想使用会话。如果我想实现webHttpBinding,我假设我必须更改我的数据发送到服务的方式,因为它不会与 JSON 一起玩?
猜你喜欢
  • 2012-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-04
  • 1970-01-01
  • 2018-10-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多