如何在WCF中设置cookie并在调用Ajax的成功函数(或其他函数)中读取它 [英] How to set a cookie in WCF and read it in the calling Ajax's success function (or elsewhere)

查看:139
本文介绍了如何在WCF中设置cookie并在调用Ajax的成功函数(或其他函数)中读取它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些jQuery JavaScript调用了简单的WCF Web服务.对我来说,在JavaScript中设置cookie并在服务器端读取它非常容易.

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.

这是代码.

客户端(JavaScript):

Client side (JavaScript):

document.cookie = "father=christmas";

服务器端(在WCF中为C#):

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"
    }
}

但是我也想在服务器上的WCF中设置一个cookie,并在客户端上读取它.这是我的代码无法执行的操作.

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.

服务器端(在WCF中为C#):

Server side (C# in WCF):

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

客户端(jQuery JavaScript):

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>');
        }
    });
});

但是xhr的值(我希望变量包含我的"cloud = lonely" cookie)是

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.我的网页(包括JavaScript)和WCF服务位于同一服务器上,因此应该没有跨域问题.)

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

我是否正确设置了响应头cookie?如果是这样,我应该在哪里找回客户的价值?如果没有,我应该怎么做?

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?

推荐答案

我希望这不是答案,但是对 Jfriend00 指出,根据此W3规范 getAllResponseHeaders()将返回除Set-Cookie头之外的所有头.而 Dan Tao 解释说,尽管浏览器会(可能吗?)在响应由响应者处理后复制cookie信息.浏览器,直到回调被调用后才会发生!丹建议在完整的回调中进行某种setTimeout交易".

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".

提请沼泽在对他对"WCF-> ASMX和Cookies"的回答是在WCF代码中使用消息检查器.

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.

我不愿意设置超时(感觉像是黑客),并且发现WCF代码更难跟消息检查器一起使用,这是逻辑的一部分,因此在等待另一个答案时,我将写响应头本身(而不是Cookie)在WCF代码中,如下所示:

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");

,然后在JavaScript/jQuery/Ajax完整处理程序中将其读取,然后将其写入Cookie,如下所示:

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;
            }
        },
    });
});

使用HTTPResponseHeader代替cookie感到不舒服,我认为cookie是为此用途而设计的,因此请提出更好的答案.

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.

这篇关于如何在WCF中设置cookie并在调用Ajax的成功函数(或其他函数)中读取它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆