3

是否可以使用 C# WCF WebHttpBinding 创建会话?(类似于带有 cookie 的 php 会话等)

4

2 回答 2

4

WCF 支持会话,但是它需要具有某种安全性的绑定,此链接应说明:

http://social.msdn.microsoft.com/Forums/is/wcf/thread/7185e8b7-d4e5-4314-a513-ec590f26ffde

您可以自己实现一个会话管理器,一个维护会话列表的静态类。每个会话都可以有一个“System.Timers.Timer”来指定会话的超时时间,然后连接一个事件处理程序以在会话计时器到期时调用。

发生这种情况时,会话管理器可以处理会话,或者如果使用 Guid(会话 ID)作为参考调用会话,则可以重置计时器以保持会话活动。

就 cookie(很可能是会话 ID)而言,您可以使用以下方法在请求中获取和设置 cookie:

    /// <summary>Gets a cookie value from cookies for given key.</summary>
    /// <param name="cookieKey">The key for the cookie value we require.</param>
    /// <returns>The cookie value.</returns>
    /// <exception cref="KeyNotFoundException">If the key was not found.</exception>
    private string GetCookieValue(string cookieKey)
    {
        string cookieHeader = WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.Cookie];
        string[] cookies = cookieHeader.Split(';');
        string result = string.Empty;
        bool cookieFound = false;

        foreach (string currentCookie in cookies)
        {
            string cookie = currentCookie.Trim();

            // Split the key/values out for each cookie.
            string[] cookieKeyValue = cookie.Split('=');

            // Compare the keys
            if (cookieKeyValue[0] == cookieKey)
            {
                result = cookieKeyValue[1];
                cookieFound = true;
                break;
            }
        }

        if (!cookieFound)
        {                
            string msg = string.Format("Unable to find cookie value for cookie key '{0}'", cookieKey);
            throw new KeyNotFoundException(msg);
        }

        // Note: The result may still be empty if there wasn't a value set for the cookie.
        // e.g. 'key=' rather than 'key=123'
        return result;
    }        

    /// <summary>Sets the cookie header.</summary>
    /// <param name="cookie">The cookie value to set.</param>
    private void SetCookie(string cookie)
    {
        // Set the cookie for all paths.
        cookie = cookie + "; path=/;" ;
        string currentHeaderValue = WebOperationContext.Current.OutgoingResponse.Headers[HttpResponseHeader.SetCookie];

        if (!string.IsNullOrEmpty(currentHeaderValue))
        {
            WebOperationContext.Current.OutgoingResponse.Headers[HttpResponseHeader.SetCookie]
                = currentHeaderValue + "\r\n" + cookie;
        }
        else
        {
            WebOperationContext.Current.OutgoingResponse.Headers[HttpResponseHeader.SetCookie] = cookie;
        }
    }

只需将 cookie 设置为“sessionId={myGuidHere}”之类的东西。

无论如何,我希望这会有所帮助..对不起,我无法发布更多示例代码,因为我正在为客户编写它。

彼得斯基

于 2011-06-08T14:17:55.757 回答
1

如果您只想使用 cookie,WebHttpBinding 已经具有该功能,但默认情况下它是关闭的。我不熟悉 PHP 会话提供的其他功能,但由于 WebHttpBinding 是建立在无会话 HTTP 请求/响应模式之上的,因此您必须按照@peteski22 在他的回答中勾勒出来的方式推出自己的功能。

于 2011-06-08T14:46:34.797 回答