是否可以使用 C# WCF WebHttpBinding 创建会话(如 php 会话)?

发布于 2024-09-03 21:09:05 字数 66 浏览 7 评论 0原文

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

Is it possible to create sessions with C# WCF WebHttpBinding? (Something like like php sessions with cookies and so on)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

鲜肉鲜肉永远不皱 2024-09-10 21:09:05

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}”之类的内容即可。

无论如何,我希望这有帮助......抱歉,我无法发布更多示例代码,因为我正在为客户编写代码。

佩泰斯基

WCF supports sessions, however it requires a binding with some security, this link should explain:

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

You could implement a session manager yourself, some static class that maintains a list of sessions. Each session can have a 'System.Timers.Timer' to specify a timeout for the session, then hook up an event handler to be called when the session timer expires.

When that happens the session manager can dispose of the session, or if the session gets called using a Guid (the session ID) as a reference then the timer can be reset keeping the session alive.

In terms of the cookie (which would most likely be the session ID) you could use methods like these to get and set the cookie in the request:

    /// <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;
        }
    }

Just set the cookie to something like "sessionId={myGuidHere}".

I hope that helps anyway.. sorry I can't post up more sample code as I'm writing it for a client.

peteski

挽袖吟 2024-09-10 21:09:05

如果您只想使用 cookie,WebHttpBinding 已经 该功能,但默认情况下处于关闭状态。我不熟悉 PHP 会话提供的其他功能,但由于 WebHttpBinding 是建立在无会话 HTTP 请求/响应模式之上的,因此您必须像 @peteski22 在他的答案中勾画出自己的功能一样。

If you just want to work with cookies, the WebHttpBinding already has that capability but it is off by default. I'm not familiar with what other capabilities PHP sessions provide but since the WebHttpBinding is built on top of the sessionless HTTP request/response pattern you'll have to roll your own as @peteski22 sketches out in his answer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文