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?