直接浏览到处理程序时在通用处理程序中创建的 Cookie 可见,但如果从 aspx 页面调用处理程序 (c#/.NET) 则不可见

Cookie created in Generic Handler visible when browsing directly to the handler but not if the handler is called from an aspx page (c#/.NET)

我在设置 cookie 的云服务器上有一个通用处理程序 (cookiecutter.ashx)。我需要从我的本地生产服务器读取这个 cookie。云服务器使用生产服务器上的域的子域(例如处理程序在 cloudserver.example.com,生产服务器在 www.example.com). The domain of the cookie is set to ".example.com". If I browse directly to cookiecutter.ashx in a browser, the cookie gets created and is visible in the browser cookie collection (using Chrome DevTools) and I can read the cookie from www.example.com. However, if I make an ajax call(JQuery) to the handler from www.example.com, the cookie can't be read from www.example.com,并且不会出现在浏览器 cookie 集合中。

如果我直接浏览到处理程序,为什么只能从 www.example.com 读取 cookie?使用 ajax?

调用处理程序时有什么方法可以获得相同的结果

我终于让它工作了。

当它不工作时,我在创建 cookie 的服务器上有以下 HTTP 响应 Header:

Access-Control-Allow-Origin = *, Access-Control-Allow-Methods = GET, POST, OPTIONS

解决方案是:

  1. 添加以下 HTTP 响应 Header:

    Access-Control-Allow-Credentials = true
    
  2. Access-Control-Allow-Origin改为https://www.example.com(实现Access-Control-Allow-Credentialsheader时不能使用通配符,必须注明出处)

  3. 将以下参数添加到对处理程序的 JQuery AJAX 调用中:

    xhrFields: {withCredentials: true}
    
  4. 创建 cookie 时将安全属性添加到 cookie (theCookie.Secure=true;)

  5. 将以下内容添加到创建 cookie 的项目的 web.config 文件的 system.web 部分:

我还应该提到,您必须为创建 cookie 的项目和读取 cookie 的项目使用相同的机器密钥。

最后,如果cookie是由.NET框架混合读取的,您还需要在机器密钥中添加CompatabilityMode。在我的例子中,所有框架都是 .NET 2.0 或更高版本,所以我使用了:compatibilityMode="Framework20SP2"

更多关于兼容模式的信息:https://docs.microsoft.com/en-us/dotnet/api/system.web.configuration.machinekeysection.compatibilitymode?view=netframework-4.8