简体   繁体   中英

Is it possible to create sessions (like php sessions) with C# WCF WebHttpBinding?

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM