2

I've got some jQuery JavaScript calling a simple WCF web service. It is fairly easy for me to set a cookie in JavaScript and read it server side.

Here's that code.

Client side (JavaScript):

document.cookie = "father=christmas";

Server side (C# in WCF):

var cookieHeader = WebOperationContext.Current.IncomingRequest.Headers[System.Net.HttpRequestHeader.Cookie];
if (!String.IsNullOrEmpty(cookieHeader))
{
    var match = cookieHeader.Split(';').Select(cookie => cookie.Split('=')).FirstOrDefault(kvp => kvp[0] == "father");
    if (match != null)
    {
        result = match[1]; // result now equals "christmas"
    }
}

But I'd also like to set a cookie in the WCF on the server and read that on the client. Here's my code that fails to do that.

Server side (C# in WCF):

WebOperationContext.Current.OutgoingResponse.Headers[System.Net.HttpResponseHeader.SetCookie] = "cloud=lonely";

Client side (jQuery JavaScript):

$(document).ready(function () {
    $.ajax({
        url: "/ScratchpadSite/Service.svc/Hallo",
        type: "POST",
        success: function (data, textStatus, jqXHR) {
            var xrh = jqXHR.getAllResponseHeaders();
            $('body').html('<p>Father ' + data.d + '<\/p>');
        },
        error: function (jqXHR, textStatus, errorThrown) {
            $('body').html('<p>' + textStatus + ': ' + errorThrown + '<\/p>');
        }
    });
});

However the value of xhr (the variable I was hoping would contain my 'cloud=lonely' cookie) is

Server: ASP.NET Development Server/10.0.0.0
Date: Wed, 04 Apr 2012 15:29:27 GMT
X-AspNet-Version: 4.0.30319
Content-Length: 17
Cache-Control: private
Content-Type: application/json; charset=utf-8
Connection: Close

(N.B. My web pages (including the JavaScript) and WCF service reside on the same server so there should be no cross-domain issues.)

Am I setting the response header cookie correctly? If so where should I be looking to find the value back on the client? If not how should I be doing this?

dumbledad
  • 16,305
  • 23
  • 120
  • 273

3 Answers3

0

I hope this isn't the answer, but there are interesting comments on this question. Jfriend00 points out that according to this W3 spec getAllResponseHeaders() will return all headers except the Set-Cookie header. And Dan Tao explains that although the browser will (might?) copy the cookie information once the response is processed by the browser, that does not happen until after the callbacks have been called! Dan suggests "some sort of setTimeout deal in the complete callback".

Another possible option (that I haven't tried) suggested by Drew Marsh in the comments to his answer to "WCF -> ASMX and Cookies" is to use a message inspector in the WCF code.

I'm reluctant to set a timeout (feels like a hack) and I find WCF code harder to follow with message inspectors part of the logic, so while waiting for another answer I'm going to write to the response header itself (rather than a cookie) in the WCF code like this:

WebOperationContext.Current.OutgoingResponse.Headers.Add("cloud", "lonely");

and then read that in the JavaScript/jQuery/Ajax complete handler and write it into a cookie then, like this:

$(document).ready(function () {
    $.ajax({
        url: "/ScratchpadSite/Service.svc/Hallo",
        type: "POST",
        success: function (data, textStatus, jqXHR) {
            $('body').html('<p>Father ' + data.d + '<\/p>');
        },
        error: function (jqXHR, textStatus, errorThrown) {
            $('body').html('<p>' + textStatus + ': ' + errorThrown + '<\/p>');
        },
        complete: function (jqXHR, textStatus) {
            var cloudsFeeling = jqXHR.getResponseHeader("cloud");
            if (cloudsFeeling) {
                document.cookie = "cloud=" + cloudsFeeling;
            }
        },
    });
});

I'm uncomfortable using the HTTPResponseHeader in place of cookies, which I thought were designed for this usage, so please please do suggest a better answer.

Community
  • 1
  • 1
dumbledad
  • 16,305
  • 23
  • 120
  • 273
0

You could deal with cookies in a very smart way using $.cookie plugin that allows you to reaad, write, and delete cookies

Hoping that helps you..

Muhammad Soliman
  • 21,644
  • 6
  • 109
  • 75
  • 1
    I'm not sure that helps - reading and writing cookies on the client is not what the question is about, rather it is about how to transfer cookies between the client and a WCF server and back to the client. – dumbledad Jun 26 '12 at 09:49
0

All cookies setted before by the same domain that you are sending HTTP request should be send automatically within the your request, in other words All cookies are sent automatically within the HTTP request such that the domain to which HTTP request is going was set that cookie before. in response way if you want to set cookie in the client, you could add the response header named "Set-Cookie"

Muhammad Soliman
  • 21,644
  • 6
  • 109
  • 75