Asp.net cookie的处理流程你真的知道吗?

ASP.NET中用户登录功能的Cookie实现 Cookie是一小段文本信息,由服务器发送至用户浏览器,并存储在本地,之后每次请求时浏览器将此信息发送回服务器。Cookie用于跟踪用户状态、保存用户偏好设置、记录用户行为等,它在保持用户会话状态方面扮演了核心角色。 阅读详情

一说到Cookie我想大家都应该知道它是一个保存在客户端,当浏览器请求一个url时,浏览器会携带相关的Cookie达到服务器端,所以服务器是可以操作Cookie的,在Response时,会把Cookie信息输出到客服端。下面我们来看一个demo吧,代码如下:


第一次请求结果如下:


第二次请求结果如下:

到这里我们可以看到第二次请求传入的Cookie正好是第一次请求返回的Cookie信息,这里的cookie信息的维护主要是我们客户端的浏览器,但是在Asp.net程序开发时,Cookie往往是在服务端程序里面写入,就如我的事例代码;很少有用客服端js实现的。现在我们就来看看asp.net服务端是如何实现读写Cookie的。

首先我们来看看HttpRequest的Cookie是如何定义的:

        public HttpCookieCollection Cookies {
            get {
                EnsureCookies();
                if (_flags[needToValidateCookies]) {
                    _flags.Clear(needToValidateCookies);
                    ValidateCookieCollection(_cookies);
                }
                return _cookies;
            }
        }
 这里的Cookie获取主要是调用一个EnsureCookies方法,EnsureCookies放主要是调用FillInCookiesCollection方法,其中Cookie属性返回的是一个HttpCookieCollection集合,
        // Populates the Cookies property but does not hook up validation.
        internal HttpCookieCollection EnsureCookies() {
            if (_cookies == null) {
                _cookies = new HttpCookieCollection(null, false);
                if (_wr != null)
                    FillInCookiesCollection(_cookies, true /*includeResponse*/);

                if (HasTransitionedToWebSocketRequest) // cookies can't be modified after the WebSocket handshake is complete
                    _cookies.MakeReadOnly();
            }
            return _cookies;
        }

public sealed class HttpCookieCollection : NameObjectCollectionBase
{
    internal HttpCookieCollection(HttpResponse response, bool readOnly) : base(StringComparer.OrdinalIgnoreCase)
    {
        this._response = response;
        base.IsReadOnly = readOnly;
    }
}

 其中这里的FillInCookiesCollection方法实现也比较复杂:

  internal void FillInCookiesCollection(HttpCookieCollection cookieCollection, bool includeResponse) {
            if (_wr == null) 
                return;

            String s = _wr.GetKnownRequestHeader(HttpWorkerRequest.HeaderCookie);
 
            // Parse the cookie server variable.
            // Format: c1=k1=v1&k2=v2; c2=... 
 
            int l = (s != null) ? s.Length : 0;
            int i = 0; 
            int j;
            char ch;

            HttpCookie lastCookie = null; 

            while (i < l) { 
                // find next ';' (don't look to ',' as per 91884) 
                j = i;
                while (j < l) { 
                    ch = s[j];
                    if (ch == ';')
                        break;
                    j++; 
                }
 
                // create cookie form string 
                String cookieString = s.Substring(i, j-i).Trim();
                i = j+1; // next cookie start 

                if (cookieString.Length == 0)
                    continue;
 
                HttpCookie cookie = CreateCookieFromString(cookieString);
 
                // some cookies starting with '$' are really attributes of the last cookie 
                if (lastCookie != null) {
                    String name = cookie.Name; 

                    // add known attribute to the last cookie (if any)
                    if (name != null && name.Length > 0 && name[0] == '$') {
                        if (StringUtil.EqualsIgnoreCase(name, "$Path")) 
                            lastCookie.Path = cookie.Value;
                        else if (StringUtil.EqualsIgnoreCase(name, "$Domain")) 
                            lastCookie.Domain = cookie.Value; 

                        continue; 
                    }
                }

                // regular cookie 
                cookieCollection.AddCookie(cookie, true);
                lastCookie = cookie; 
 
                // goto next cookie
            } 

            // Append response cookies
            if (includeResponse) {
                // If we have a reference to the response cookies collection, use it directly 
                // rather than going through the Response object (which might not be available, e.g.
                // if we have already transitioned to a WebSockets request). 
                HttpCookieCollection storedResponseCookies = _storedResponseCookies; 
                if (storedResponseCookies == null && !HasTransitionedToWebSocketRequest && Response != null) {
                    storedResponseCookies = Response.GetCookiesNoCreate(); 
                }

                if (storedResponseCookies != null && storedResponseCookies.Count > 0) {
                    HttpCookie[] responseCookieArray = new HttpCookie[storedResponseCookies.Count]; 
                    storedResponseCookies.CopyTo(responseCookieArray, 0);
                    for (int iCookie = 0; iCookie < responseCookieArray.Length; iCookie++) 
                        cookieCollection.AddCookie(responseCookieArray[iCookie], append: true); 
                }
 
                // release any stored reference to the response cookie collection
                _storedResponseCookies = null;
            }
        } 
说简单一点它主要调用HttpWorkerRequest的GetKnownRequestHeader方法获取浏览器传进来的Cookie字符串信息,然后再把这些信息根据 ;来分隔成多个HttpCookie实例。把这些HttpCookie实例添加到传进来的HttpCookieCollection参数。

这里HttpWorkerRequest继承结果如下:

internal class ISAPIWorkerRequestInProcForIIS7 : ISAPIWorkerRequestInProcForIIS6
internal class ISAPIWorkerRequestInProcForIIS6 : ISAPIWorkerRequestInProc
internal class ISAPIWorkerRequestInProc : ISAPIWorkerRequest
internal abstract class ISAPIWorkerRequest : HttpWorkerRequest

其中 GetKnownRequestHeader方法的实现主要是在ISAPIWorkerRequest中,其GetKnownRequestHeader主要是调用了它的ReadRequestHeaders私有方法,在ReadRequestHeaders方法中主要是调用它的this.GetServerVariable("ALL_RAW")方法,所以我们可以认为this.GetServerVariable("ALL_RAW")这个方法是获取客户端传来的Cookie参数,而GetServerVariable方法的实现主要是在ISAPIWorkerRequestInProc 类,具体实现非常复杂。

这里的GetKnownRequestHeader方法实现非常复杂我们也就不去深研它了,我们只要知道调用这个方法就会返回Cookie的所有字符串信息。在这个方法里面还调用了一个CreateCookieFromString方法,根据字符串来创建我们的HttpCookie实例。CreateCookieFromString方法实现如下:

  internal static HttpCookie CreateCookieFromString(String s) { 
            HttpCookie c = new HttpCookie();
 
            int l = (s != null) ? s.Length : 0; 
            int i = 0;
            int ai, ei; 
            bool firstValue = true;
            int numValues = 1;

            // Format: cookiename[=key1=val2&key2=val2&...] 

            while (i < l) { 
                //  find next & 
                ai = s.IndexOf('&', i);
                if (ai < 0) 
                    ai = l;

                // first value might contain cookie name before =
                if (firstValue) { 
                    ei = s.IndexOf('=', i);
 
                    if (ei >= 0 && ei < ai) { 
                        c.Name = s.Substring(i, ei-i);
                        i = ei+1; 
                    }
                    else if (ai == l) {
                        // the whole cookie is just a name
                        c.Name = s; 
                        break;
                    } 
 
                    firstValue = false;
                } 

                // find '='
                ei = s.IndexOf('=', i);
 
                if (ei < 0 && ai == l && numValues == 0) {
                    // simple cookie with simple value 
                    c.Value = s.Substring(i, l-i); 
                }
                else if (ei >= 0 && ei < ai) { 
                    // key=value
                    c.Values.Add(s.Substring(i, ei-i), s.Substring(ei+1, ai-ei-1));
                    numValues++;
                } 
                else {
                    // value without key 
                    c.Values.Add(null, s.Substring(i, ai-i)); 
                    numValues++;
                } 

                i = ai+1;
            }
 
            return c;
        } 
我们平时很少用到HttpCookie的Values属性,所以这个属性大家还是需要注意一下,这个方法就是把一个cookie的字符串转化为相应的HttpCookie实例。
现在我们回到HttpRequest的Cookies属性中来,这里有一个关于Cookie的简单验证ValidateCookieCollection方法,

 private void ValidateCookieCollection(HttpCookieCollection cc) {
            if (_enableGranularValidation) {
                // Granular request validation is enabled - validate collection entries only as they're accessed.
                cc.EnableGranularValidation((key, value) => ValidateString(value, key, RequestValidationSource.Cookies));
            }
            else {
                // Granular request validation is disabled - eagerly validate all collection entries.
                int c = cc.Count;
 
                for (int i = 0; i < c; i++) {
                    String key = cc.GetKey(i);
                    String val = cc.Get(i).Value;

                    if (!String.IsNullOrEmpty(val))
                        ValidateString(val, key, RequestValidationSource.Cookies);
                }
            }
        }

其中HttpCookieCollection的EnableGranularValidation实现如下:

 internal void EnableGranularValidation(ValidateStringCallback validationCallback)
    {
        this._keysAwaitingValidation = new HashSet<string>(this.Keys.Cast<string>(), StringComparer.OrdinalIgnoreCase);
        this._validationCallback = validationCallback;
    }

    private void EnsureKeyValidated(string key, string value)
    {
        if ((this._keysAwaitingValidation != null) && this._keysAwaitingValidation.Contains(key))
        {
            if (!string.IsNullOrEmpty(value))
            {
                this._validationCallback(key, value);
            }
            this._keysAwaitingValidation.Remove(key);
        }
    }

到这里我们知道默认从浏览器发送到服务器端的Cookie都是需要经过次验证的。这里的ValidateString方法具体实现我们就不说了,不过大家需要知道它是调用了RequestValidator.Current.IsValidRequestString方法来实现验证的,有关RequestValidator的信息大家可以查看HttpRequest的QueryString属性 的一点认识 。现在我们获取Cookie已经基本完成了。那么我们接下来看看是如何添加Cookie的了。

首先我们来看看HttpResponse的Cookie属性:

public HttpCookieCollection Cookies
{
    get
    {
        if (this._cookies == null)
        {
            this._cookies = new HttpCookieCollection(this, false);
        }
        return this._cookies;
    }
}
接下来我们看看HttpCookie的实现如下:

  public sealed class HttpCookie {
        private String _name;
        private String _path = "/";
        private bool _secure; 
        private bool _httpOnly;
        private String _domain; 
        private bool _expirationSet; 
        private DateTime _expires;
        private String _stringValue; 
        private HttpValueCollection _multiValue;
        private bool _changed;
        private bool _added;
 
        internal HttpCookie() {
            _changed = true; 
        } 

        /* 
         * Constructor - empty cookie with name
         */

        /// <devdoc> 
        ///    <para>
        ///       Initializes a new instance of the <see cref='System.Web.HttpCookie'/> 
        ///       class. 
        ///    </para>
        /// </devdoc> 
        public HttpCookie(String name) {
            _name = name;

            SetDefaultsFromConfig(); 
            _changed = true;
        } 
 
        /*
         * Constructor - cookie with name and value 
         */

        /// <devdoc>
        ///    <para> 
        ///       Initializes a new instance of the <see cref='System.Web.HttpCookie'/>
        ///       class. 
        ///    </para> 
        /// </devdoc>
        public HttpCookie(String name, String value) { 
            _name = name;
            _stringValue = value;

            SetDefaultsFromConfig(); 
            _changed = true;
        } 
 
        private void SetDefaultsFromConfig() {
            HttpCookiesSection config = RuntimeConfig.GetConfig().HttpCookies; 
            _secure = config.RequireSSL;
            _httpOnly = config.HttpOnlyCookies;

            if (config.Domain != null && config.Domain.Length > 0) 
                _domain = config.Domain;
        } 
 
        /*
         * Whether the cookie contents have changed 
         */
        internal bool Changed {
            get { return _changed; }
            set { _changed = value; } 
        }
 
        /* 
         * Whether the cookie has been added
         */ 
        internal bool Added {
            get { return _added; }
            set { _added = value; }
        } 

        // DevID 251951	Cookie is getting duplicated by ASP.NET when they are added via a native module 
        // This flag is used to remember that this cookie came from an IIS Set-Header flag, 
        // so we don't duplicate it and send it back to IIS
        internal bool FromHeader { 
            get;
            set;
        }
 
        /*
         * Cookie name 
         */ 

        /// <devdoc> 
        ///    <para>
        ///       Gets
        ///       or sets the name of cookie.
        ///    </para> 
        /// </devdoc>
        public String Name { 
            get { return _name;} 
            set {
                _name = value; 
                _changed = true;
            }
        }
 
        /*
         * Cookie path 
         */ 

        /// <devdoc> 
        ///    <para>
        ///       Gets or sets the URL prefix to transmit with the
        ///       current cookie.
        ///    </para> 
        /// </devdoc>
        public String Path { 
            get { return _path;} 
            set {
                _path = value; 
                _changed = true;
            }
        }
 
        /*
         * 'Secure' flag 
         */ 

        /// <devdoc> 
        ///    <para>
        ///       Indicates whether the cookie should be transmitted only over HTTPS.
        ///    </para>
        /// </devdoc> 
        public bool Secure {
            get { return _secure;} 
            set { 
                _secure = value;
                _changed = true; 
            }
        }

        /// <summary> 
        /// Determines whether this cookie is allowed to participate in output caching.
        /// </summary> 
        /// <remarks> 
        /// If a given HttpResponse contains one or more outbound cookies with Shareable = false (the default value),
        /// output caching will be suppressed for that response. This prevents cookies that contain potentially 
        /// sensitive information, e.g. FormsAuth cookies, from being cached in the response and sent to multiple
        /// clients. If a developer wants to allow a response containing cookies to be cached, he should configure
        /// caching as normal for the response, e.g. via the OutputCache directive, MVC's [OutputCache] attribute,
        /// etc., and he should make sure that all outbound cookies are marked Shareable = true. 
        /// </remarks>
        public bool Shareable { 
            get; 
            set; // don't need to set _changed flag since Set-Cookie header isn't affected by value of Shareable
        } 

        /// <devdoc>
        ///    <para>
        ///       Indicates whether the cookie should have HttpOnly attribute 
        ///    </para>
        /// </devdoc> 
        public bool HttpOnly { 
            get { return _httpOnly;}
            set { 
                _httpOnly = value;
                _changed = true;
            }
        } 

        /* 
         * Cookie domain 
         */
 
        /// <devdoc>
        ///    <para>
        ///       Restricts domain cookie is to be used with.
        ///    </para> 
        /// </devdoc>
        public String Domain { 
            get { return _domain;} 
            set {
                _domain = value; 
                _changed = true;
            }
        }
 
        /*
         * Cookie expiration 
         */ 

        /// <devdoc> 
        ///    <para>
        ///       Expiration time for cookie (in minutes).
        ///    </para>
        /// </devdoc> 
        public DateTime Expires {
            get { 
                return(_expirationSet ? _expires : DateTime.MinValue); 
            }
 
            set {
                _expires = value;
                _expirationSet = true;
                _changed = true; 
            }
        } 
 
        /*
         * Cookie value as string 
         */

        /// <devdoc>
        ///    <para> 
        ///       Gets
        ///       or 
        ///       sets an individual cookie value. 
        ///    </para>
        /// </devdoc> 
        public String Value {
            get {
                if (_multiValue != null)
                    return _multiValue.ToString(false); 
                else
                    return _stringValue; 
            } 

            set { 
                if (_multiValue != null) {
                    // reset multivalue collection to contain
                    // single keyless value
                    _multiValue.Reset(); 
                    _multiValue.Add(null, value);
                } 
                else { 
                    // remember as string
                    _stringValue = value; 
                }
                _changed = true;
            }
        } 

        /* 
         * Checks is cookie has sub-keys 
         */
 
        /// <devdoc>
        ///    <para>Gets a
        ///       value indicating whether the cookie has sub-keys.</para>
        /// </devdoc> 
        public bool HasKeys {
            get { return Values.HasKeys();} 
        } 

        private bool SupportsHttpOnly(HttpContext context) { 
            if (context != null && context.Request != null) {
                HttpBrowserCapabilities browser = context.Request.Browser;
                return (browser != null && (browser.Type != "IE5" || browser.Platform != "MacPPC"));
            } 
            return false;
        } 
 
        /*
         * Cookie values as multivalue collection 
         */

        /// <devdoc>
        ///    <para>Gets individual key:value pairs within a single cookie object.</para> 
        /// </devdoc>
        public NameValueCollection Values { 
            get { 
                if (_multiValue == null) {
                    // create collection on demand 
                    _multiValue = new HttpValueCollection();

                    // convert existing string value into multivalue
                    if (_stringValue != null) { 
                        if (_stringValue.IndexOf('&') >= 0 || _stringValue.IndexOf('=') >= 0)
                            _multiValue.FillFromString(_stringValue); 
                        else 
                            _multiValue.Add(null, _stringValue);
 
                        _stringValue = null;
                    }
                }
 
                _changed = true;
 
                return _multiValue; 
            }
        } 

        /*
         * Default indexed property -- lookup the multivalue collection
         */ 

        /// <devdoc> 
        ///    <para> 
        ///       Shortcut for HttpCookie$Values[key]. Required for ASP compatibility.
        ///    </para> 
        /// </devdoc>
        public String this[String key]
        {
            get { 
                return Values[key];
            } 
 
            set {
                Values[key] = value; 
                _changed = true;
            }
        }
 
        /*
         * Construct set-cookie header 
         */ 
        internal HttpResponseHeader GetSetCookieHeader(HttpContext context) {
            StringBuilder s = new StringBuilder(); 

            // cookiename=
            if (!String.IsNullOrEmpty(_name)) {
                s.Append(_name); 
                s.Append('=');
            } 
 
            // key=value&...
            if (_multiValue != null) 
                s.Append(_multiValue.ToString(false));
            else if (_stringValue != null)
                s.Append(_stringValue);
 
            // domain
            if (!String.IsNullOrEmpty(_domain)) { 
                s.Append("; domain="); 
                s.Append(_domain);
            } 

            // expiration
            if (_expirationSet && _expires != DateTime.MinValue) {
                s.Append("; expires="); 
                s.Append(HttpUtility.FormatHttpCookieDateTime(_expires));
            } 
 
            // path
            if (!String.IsNullOrEmpty(_path)) { 
                s.Append("; path=");
                s.Append(_path);
            }
 
            // secure
            if (_secure) 
                s.Append("; secure"); 

            // httponly, Note: IE5 on the Mac doesn't support this 
            if (_httpOnly && SupportsHttpOnly(context)) {
                s.Append("; HttpOnly");
            }
 
            // return as HttpResponseHeader
            return new HttpResponseHeader(HttpWorkerRequest.HeaderSetCookie, s.ToString()); 
        } 
    }
现在我们回到HttpCookieCollection的Add方法看看,

     public void Add(HttpCookie cookie) {
            if (_response != null)
                _response.BeforeCookieCollectionChange();
 
            AddCookie(cookie, true);

            if (_response != null)
                _response.OnCookieAdd(cookie);
        }
 
public sealed class HttpResponse
{
  internal void BeforeCookieCollectionChange()
   {
    if (this._headersWritten)
    {
        throw new HttpException(SR.GetString("Cannot_modify_cookies_after_headers_sent"));
    }

  }
 internal void OnCookieAdd(HttpCookie cookie)
 {
    this.Request.AddResponseCookie(cookie);
 }
}
public sealed class HttpRequest
{
  internal void AddResponseCookie(HttpCookie cookie)
  {
    if (this._cookies != null)
    {
        this._cookies.AddCookie(cookie, true);
    }
    if (this._params != null)
    {
        this._params.MakeReadWrite();
        this._params.Add(cookie.Name, cookie.Value);
        this._params.MakeReadOnly();
    }
 }
}

到这里我们应该知道每添加或修改一个Cookie都会调用HttpResponse的BeforeCookieCollectionChange和OnCookieAdd方法,BeforeCookieCollectionChange是确认我们的cookie是否可以添加的,以前在项目中就遇到这里的错误信息说什么“在header发送后不能修改cookie”,看见默认情况下_headersWritten是false,那么它通常在哪里被设置为true了,在HttpReaponse的BeginExecuteUrlForEntireResponse、Flush、EndFlush方法中被设置为true,而我们最常接触到的还是Flush方法。这里的OnCookieAdd方法确保Cookie实例同时也添加到HttpRequest中。

  internal void AddCookie(HttpCookie cookie, bool append) {
            ThrowIfMaxHttpCollectionKeysExceeded();
 
            _all = null;
            _allKeys = null;

            if (append) {
                // DevID 251951    Cookie is getting duplicated by ASP.NET when they are added via a native module
                // Need to not double add response cookies from native modules
                if (!cookie.FromHeader) {
                    // mark cookie as new
                    cookie.Added = true;
                }
                BaseAdd(cookie.Name, cookie);
            }
            else {
                if (BaseGet(cookie.Name) != null) {
                    // mark the cookie as changed because we are overriding the existing one
                    cookie.Changed = true;
                }
                BaseSet(cookie.Name, cookie);
            }
        }
         private void ThrowIfMaxHttpCollectionKeysExceeded() {
            if (Count >= AppSettings.MaxHttpCollectionKeys) {
                throw new InvalidOperationException(SR.GetString(SR.CollectionCountExceeded_HttpValueCollection, AppSettings.MaxHttpCollectionKeys));
            }

        }

这里的AddCookie方法也非常简单,不过每次添加都会去检查Cookie的个数是否超过最大值。其实添加Cookie还可以调用HttpResponse的AppendCookie方法,

public void AppendCookie(HttpCookie cookie)
{
    if (this._headersWritten)
    {
        throw new HttpException(SR.GetString("Cannot_append_cookie_after_headers_sent"));
    }
    this.Cookies.AddCookie(cookie, true);
    this.OnCookieAdd(cookie);
}
这里它的实现和HttpCookieCollection的     public void Add(HttpCookie cookie)方法实现一致。
 同样我们也知道这些Cookie是在HttpResponse的GenerateResponseHeadersForCookies方法中被使用,
其中GenerateResponseHeadersForCookies方法的实现如下:

  internal void GenerateResponseHeadersForCookies()
        { 
            if (_cookies == null || (_cookies.Count == 0 && !_cookies.Changed)) 
                return; // no cookies exist
 
            HttpHeaderCollection headers = Headers as HttpHeaderCollection;
            HttpResponseHeader cookieHeader = null;
            HttpCookie cookie = null;
            bool needToReset = false; 

            // Go through all cookies, and check whether any have been added 
            // or changed.  If a cookie was added, we can simply generate a new 
            // set cookie header for it.  If the cookie collection has been
            // changed (cleared or cookies removed), or an existing cookie was 
            // changed, we have to regenerate all Set-Cookie headers due to an IIS
            // limitation that prevents us from being able to delete specific
            // Set-Cookie headers for items that changed.
            if (!_cookies.Changed) 
            {
                for(int c = 0; c < _cookies.Count; c++) 
                { 
                    cookie = _cookies[c];
                    if (cookie.Added) { 
                        // if a cookie was added, we generate a Set-Cookie header for it
                        cookieHeader = cookie.GetSetCookieHeader(_context);
                        headers.SetHeader(cookieHeader.Name, cookieHeader.Value, false);
                        cookie.Added = false; 
                        cookie.Changed = false;
                    } 
                    else if (cookie.Changed) { 
                        // if a cookie has changed, we need to clear all cookie
                        // headers and re-write them all since we cant delete 
                        // specific existing cookies
                        needToReset = true;
                        break;
                    } 
                }
            } 
 

            if (_cookies.Changed || needToReset) 
            {
                // delete all set cookie headers
                headers.Remove("Set-Cookie");
 
                // write all the cookies again
                for(int c = 0; c < _cookies.Count; c++) 
                { 
                    // generate a Set-Cookie header for each cookie
                    cookie = _cookies[c]; 
                    cookieHeader = cookie.GetSetCookieHeader(_context);
                    headers.SetHeader(cookieHeader.Name, cookieHeader.Value, false);
                    cookie.Added = false;
                    cookie.Changed = false; 
                }
 
                _cookies.Changed = false; 
            }
        } 
这里我们还是来总结一下吧: 在HttpWorkerRequest中我们调用GetKnownRequestHeader方法来获取Cookie的字符串形式,然后再将这里的字符串转化为HttpCookie集合供HttpRequest使用,在HttpResponse中的GenerateResponseHeadersForCookies方法中会处理我们的cookie实例,调用cookie的GetSetCookieHeader方法得到HttpCookie对应的字符串值,然后把该值添加到HttpHeaderCollection 集合中(或者修改已有的值)。在获取cookie是这里有一个验证需要我们注意的就是RequestValidator.Current.IsValidRequestString方法。   在添加或修改Cookie是有2个地方的检查(1)检查Cookie的个数是否达到我们配置的cookie最大个数,(2)现在是否已经写入头信息,如果头信息已经写了则不能操作cookie。



VerilogEval实战指南:从基准测试到模型微调的全流程解析 本文提供了VerilogEval实战指南,详细解析了从基准测试到模型微调的全流程。VerilogEval是一个自动化、标准化的测试框架,用于客观评估大语言模型生成Verilog硬件代码的能力。文章涵盖了环境搭建、核心机制解析、利用其生成合成数据进行模型微调的策略,以及如何将其工程化集成到自动化评估流程中,为硬件设计领域的AI应用提供了完整的方法论。 阅读详情

相关推荐

Halcon一维测量实战:从measure_pos与measure_pairs的底层原理到精准应用

本文深入解析Halcon中measure_pos与measure_pairs算子的底层原理与精准应用,涵盖参数调优、测量矩形方向设置及典型工业场景实战。通过对比分析,揭示两者在一维测量中的核心差异与适用场景,提供从基础到高级的完整解决方案,助力工业视觉检测精度提升。

weixin_42525551的博客 431

[APS.NET]Cookie

提高用户体验的缓存。

Stephanie翟倩 317

Procedural modeling

What is procedural modeling? One content generation option is modeling buildings, plants, clouds, cities, and worlds using an underlying system of rules. 1 Procedural Modeling: Grammars A rule-based generative system loosely organized as: ...

qq_24505417的博客 719

ASP.NET Core Cookie SameSite

在较多的项目中,Cookie 是比较常用的一种状态保持的选择。比如常见的例子:用户登录成功后,服务器通过 set-cookie 将会话Id设置到当前域下,前端在调用后端接口时,会自动将同...

dotNET跨平台 1149

永磁同步电机矢量控制——从三相静止坐标系到d-q坐标系的数学转换

本文深入解析了永磁同步电机矢量控制的核心——从三相静止坐标系到d-q旋转坐标系的数学转换。通过Clark变换和Park变换,将复杂的三相交流系统解耦为易于控制的直流量,从而实现对电机转矩和磁场的独立、精准控制。文章结合物理图像与工程实践,详细阐述了坐标变换的原理、公式推导及其在磁场定向控制(FOC)中的关键作用。

weixin_29294395的博客 122

Autosar诊断实战系列05-Dcm之0x27加解密服务配置开发详解

UDS 0x27服务实战开发介绍,对解锁尝试次数及delay时间进一步解释。

initiallizer的博客 2000

详解Asp.Net Core中的Cookies

目录 详解Asp.Net Core中的cookies 搞懂cookies Asp.Net中cookies的实现 从http中获取cookies 将cookies写入http中 总结及感想 详解Asp.Net Core中的cookies 搞懂cookies 我之前写过一篇文章来介绍cookies,如果你对cookies不是很了解请移步理解c...

weixin_34361881的博客 1235

【AI测试必学】DeepSeek API 快速入门:获取 API Key 与调用 API 步骤详解

DeepSeek API 使用与 OpenAI 兼容的格式,可以通过修改配置使用 OpenAI SDK。生成的 API Key 只会显示一次,请妥善保存。注册并登录账号,进入左侧导航栏的。创建 API Key。

blues_C的博客 1万+

.NETFramework-Web:HttpCookie

ylbtech-.NETFramework-Web:HttpCookie 1.程序集 System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a返回顶部 1、 #region 程序集 System.Web, Version=4.0.0...

weixin_30318645的博客 152

如何使用手机编程查看妻子的微信

在本文中,我将向您介绍如何使用编程技巧来查看妻子的微信消息。请注意,隐私是非常重要的,因此在进行此类操作之前,请确保您已经获得了妻子的明确许可。此外,请记住,未经对方授权访问他人的通信是违法行为,因此请谨慎行事。请记住,这仅仅是使用编程技巧来查看妻子的微信消息的一种方法。itchat是一个用于微信个人账号的API,可以通过Python编程语言与微信进行交互。一旦我们登录成功,我们可以使用itchat库获取妻子的微信好友列表。我们可以使用itchat库来查看妻子的微信消息。步骤 5:查看妻子的微信消息。

TechPulseZ的博客 478

【芯片设计- RTL 编译与仿真 1.2 -- Visualizer 常用使用命令】

打开波形后,如果想要看到所有信号的数据,可以点击下图中红框中的按钮,因为默认verdi 默认并不是显示所用信号。如果想统计某一个信号中有多少笔数据时,可以使用 Expression->Edege Count 功能。如下图所示,如果没有打开前导0的功能时,当某一笔数据位0时,只会显示1个0。如果需要将波形的数据导出到文本文件时,可以按照下面步骤进行。打开前导0功能之后,会根据数据位宽来显示对应0的个数。

CodingCos的博客 2055

基于 YOLOv26 的车辆违规停车检测系统:实时监控

本文提出了一种基于YOLOv26的车辆违规停车实时检测系统。系统采用多模块架构,包括视频预处理、YOLOv26目标检测、DeepSORT目标跟踪、停车区域定义、行为分析和违规判定等功能模块。关键技术包括使用YOLOv26s模型进行车辆检测,结合DeepSORT算法实现车辆跟踪,支持多种停车区域定义方式(多边形、矩形、限时区域等)。系统通过边缘计算平台部署,实现了对道路边、禁止停车区等场景的实时监控,能够准确识别长时间停车、禁止区域停车等违规行为,并触发告警机制。实验结果表明,该系统在车辆检测准确率和违规判定

一键难忘的博客 778

ASP.NET Cookie对象

Cookies 是一种能够让网站服务器把少量数据储存到客户端的硬盘或内存中,或是从客户端的硬盘读取数据的一种技术。Cookies 是当用户浏览某网站时,由 Web 服务器置于用户硬盘上的一个非常小的文本文件(大多数浏览器支持最大保存4096 字节的 Cookies,限制了 Cookies的大小),它可以记录用户的 ID、密码浏览过的网页停留的时间等信息。

m0_73983392的博客 1994

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

ASP.NET Cookie

什么是Cookie? Cookie是一小段文本信息,伴随着用户请求和页面在web服务器和浏览器之间传递,Cookie包含每次用户访问站点时web应用程序读可以读取信息 例如,如果在用户请求站点中的页面时应用程序发送给该用户的不仅仅是一个页面,还有一个包含日期和时间的 Cookie,用户的浏览器在获得页面的同时还获得了该 Cookie,并将它存储在用户硬盘上的某个文件夹中。 以后,如果该用户再次请求...

张兴军的博客 3194

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

关于Asp.net中Cookie的问题

关于Asp.net应用中cookie的问题处理: 1、在应用程序中有时会出现cookie混乱的问题,主要问题在RemoveCookie上,解决办法:        ///        /// 移除cookie,将Request和Response两个集合中的都清理       ///  Code by KentLi       ///        /// co

李洪根的blog-专注软件开发技术 7771

无 Cookie 的 ASP.NET

无 Cookie 的 ASP.NET-- 不使用 Cookie 的 ASP.NET 会话管理:风险与利益发布日期: 7/18/2005 | 更新日期: 7/18/2005Dino EspositoWintellect摘要:Dino 探究无 Cookie 会话的优缺点,并且讨论为什么应该避免在会话状态中存储有价值的信息。本页内容Cookies 是不是一个问题?进入无 Cookie 会话实现 优点缺点

FreeXploiT 2396

ASP.NET 中 Cookie 的基本知识

ASP.NET 中 Cookie 的基本知识 Mike PopeVisual Basic User EducationMicrosoft Corporation 2003年1月 摘要:本文介绍如何使用 Visual Basic 在 ASP.NET Web 应用程序中读写 HTTP Cookie。适用于: ASP.NET Microsoft® Visual Studio® .NE

wenejiang的专栏 927

ASP.NET与ASP.NET Core用户验证Cookie并存解决方案

在你将现有的用户登录(Sign In)站点从ASP.NET迁移至ASP.NET Core时,你将面临这样一个问题——如何让ASP.NET与ASP.NET Core用户验证Cookie并存,让ASP.NET应用与ASP.NET Core应用分别使用各自的Cookie?因为ASP.NET用的是FormsAuthentication,ASP.NET Core用的是claims-based authent

dotNET跨平台 1350

ASP.NET Cookie 概述

ASP.NET Cookie 概述 摘自msdn:http://msdn.microsoft.com/zh-cn/library/ms178194(VS.80).aspx Cookie 提供了一种在 Web 应用程序中存储用户特定信息的方法。例如,当用户访问您的站点时,您可以使用 Cookie 存储用户首选项或其他信息。当该用户再次访问您的网站时,应用程序便可以检索以前存储的信...

weixin_34293246的博客 322

asp.net,cookie,写cookie,取cookie

Cookie是一段文本信息,在客户端存储 Cookie 是 ASP.NET 的会话状态将请求与会话关联的方法之一。Cookie 也可以直接用于在请求之间保持数据,但数据随后将存储在客户端并随每个请求一起发送到服务器。浏览器对 Cookie 的大小有限制,因此,只有不超过 4096 字节才能保证被接受。编写Cookie//方式1:Response.Cookies["username"].value="mike";Res...

忆水思寒的博客 403

Asp.net中Cookie简明参考

Asp.net中Cookie简明参考一       写入Cookie1.   Name 和 Value 属性由程序设定,默认值都是空引用。2.   Domain属性的默认值为当前URL的域名部分,不管发出这个cookie的页面在哪个目录下的。例如,http://www.kent.com/application1/login.aspx 页面中发出一个cookie,Domain属性缺省就是

chnking的专栏 1810

无 Cookie 的 ASP.NET----不使用 Cookie 的 ASP.NET 会话管理:风险与利益

      我们承认这一点 — 我们对会话状态这一概念是如此习以为常,以至于我们忘记了会话状态是在 1997 年用 Active Server Pages (ASP) 引入的一个手段。会话状态使开发人员能够在用户与应用程序交互这段时间内持久保存有关该用户的一块信息。特定于用户的信息通常会保留 20 分钟长的时段,而每当用户返回该站点时,该时段都将重新开始计时。当用户首次连接到站点时,将以内存块

赛跑的专栏 1588
上一篇: asp.net 动态创建TextBox控件 如何加载状态信息
下一篇: SSIS中代码页(Code Page)问题
dz45693
博客等级 码龄20年 743粉丝 579原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值