代码之家  ›  专栏  ›  技术社区  ›  JCCyC

我需要开发一个只通过HTTP/HTTPS公开的WCF服务。如何使用HTTP cookie?

  •  0
  • JCCyC  · 技术社区  · 15 年前

    首先,我承认我是WCF的新手。仍然没有脱离训练轮。

    我被指派开发一个WCF服务,部分要求是,一种“会话令牌”需要作为HTTP cookie与每个请求一起传递。(可以预见,此类令牌需要在此类服务中成功的“登录”调用的HTTP响应头中生成)。

    这是直截了当的吗?

    3 回复  |  直到 15 年前
        1
  •  2
  •   James King    15 年前

    免责声明:您不应该这样做,因为它强制WCF服务表现为Web服务。但是如果你需要饼干,继续读下去。

    如果您只需要会话ID,可以从以下位置获取:

    OperationContext.Current.SessionId      
    

    如果你需要饼干,你需要跳过一些圈。它的要点是(1)设置ASP.NET兼容性,(2)引用httpContext.current属性。

    您的服务将需要使用wshttpbinding(或另一个支持会话的绑定)。如果将项目创建为宿主在IIS中的WCF服务,则默认情况下将获得这些服务。您还需要在配置文件中设置ASP.NET兼容性。

    <system.serviceModel>
      <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
      <bindings>
        <wsHttpBinding>
          <binding name="MyBinding" allowCookies="false" ... </binding>
        </wsHttpBinding>
      </bindings>
    

    (参见链接 here 为什么我有allowcookies=false)

    要启用会话,请在WCF服务约定上设置以下内容

    [ServiceContract(SessionMode=SessionMode.Required)]
    public interface IMyWcfService {...}
    

    您可能还需要在服务本身上设置ServiceBehavior(Persession是默认设置),并且需要设置ASP.NET兼容性。

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
    [AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Required)]
    public class MyWcfService : IMyWcfService {...}
    

    您可以访问的一些相关属性:

    // Gives you the current session id as a string
    HttpContext.Current.Session.SessionID  
    
    // Indicates whether the service is using sessionless cookies
    HttpContext.Current.Session.CookieMode
    
    // Indicates whether the session id is stored in the url or in an HTTP cookie 
    HttpContext.Current.Session.IsCookieless
    
    // The cookies themselves
    HttpContext.Current.Request.Cookies
    HttpContext.Current.Response.Cookies
    
    // The session and cache objects
    HttpContext.Current.Cache
    HttpContext.Current.Session
    

    WCF服务中会话的链接:
    http://msdn.microsoft.com/en-us/library/ms733040.aspx

    HTH
    詹姆斯

        2
  •  0
  •   Ivan Milosavljevic    15 年前

    关于msdn的这个主题可以帮助你 http://msdn.microsoft.com/en-us/library/bb398778.aspx .

    此外,这还可以帮助您在IIS中托管您的wcf服务: http://msdn.microsoft.com/en-us/library/aa702682.aspx 和 http://msdn.microsoft.com/en-us/library/bb332338.aspx (使用互联网信息服务托管)

        3
  •  0
  •   dexter    15 年前

    这只是部分地回答了您的问题,但会让您从config开始。 在服务配置部分下的配置文件中,创建基本的HTTP绑定,如下所示:

    <system.serviceModel> 
            <bindings>
      <basicHttpBinding>
          <binding name="myHttpBinding" allowCookies="true">
    
          </binding>
    
      </basicHttpBinding>
    </system.serviceModel>
    

    然后阅读WCF绑定和端点配置。

    推荐文章