大网数据广告活动
Web服务器与PHP

Cookies added by HttpModule are unusable

· 52CE 我爱测

This article provides resolutions for the problem where cookie doesn't display in the native IHttpRequest object When you use the Cookies collection from either the managed HttpRequest or HttpResponse objects to add a cookie.

This article helps you resolve the problem where cookies that are added by a managed isn't available to native IHttpModules or IHttpHandlers.

Original product version:   Internet Information Services
Original KB number:   2666571

Symptoms

When using the Cookies collection from either the managed HttpRequest or HttpResponse objects to add a cookie, the cookie doesn't show up in the native IHttpRequest object.

Cause

The Cookies collection in the managed HttpRequest and HttpResponse objects don't have a corresponding collection in the IHttpRequest or IHttpResponse object in Internet Information Services (IIS). So adding or modifying either of these collections doesn't modify the Cookie header in the IHttpRequest object.

Resolution

To modify a specific cookie in the Cookie header of the native IHttpRequest object from managed code, modify the Cookie header directly in the managed HttpRequest object's Header collection, instead of via the Cookies collection.

More information

The following sample means managed HttpModule code would add the cookie to the headers in the IHttpRequest object in the IIS pipeline.

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

namespace AddCookieModule
{
    public class AddCookieClass : IHttpModule
    {
        private void Application_BeginRequest(Object source EventArgs e)
        {
            HttpApplication application = (HttpApplication)source;
            HttpContext context = application.Context;
            HttpCookie testCookie = new HttpCookie("testCookie",
            DateTime.Now.ToString());
            testCookie.Expires = DateTime.Now.AddYears(5);
            context.Request.Headers.Add("Cookie",
                                        "testCookie=" + testCookie.Value);
            context.Response.Cookies.Add(testCookie);
        }

        public void Dispose()
        {
            // nothing to do.
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest +=
                (new EventHandler(this.Application_BeginRequest));
        }
    }
}

Source: Microsoft Learn / IT Pro troubleshooting by Microsoft and contributors. Documentation licensed CC BY 4.0. Code samples are covered by the MIT License. Converted from Markdown, with links normalized and embedded media omitted.

资料来源与适用范围

资料来源
Microsoft Learn / IT Pro troubleshooting
适用范围
See source applicability · Source date 03/26/2020
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY 4.0 (documentation), MIT (code samples)

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。