Requests. Cookies and response. Cookies

Source: Internet
Author: User

 

Yesterday I was bored and saw a piece of news in the garden. A 8-Year-Old elementary school student rejected his confession: he was defeated by an iPhone. He saw this article appear in the Technology Garden (probably because of an iPhone keyword ), in addition, the news reading volume is much higher than that at the same time, which makes it difficult for programmers to sigh. In fact, it also has a self-mocking nature (because it is indeed a bit confused recently and cannot be determined to read some technical articles, A little longer, after seeing it, I often collect my favorites or mark things and comfort myself to watch it later. In fact, I seldom see it again.) It was really a relentless ridicule from my classmates in the garden. Haha, bored programmers are many...

In addition, I also made some "things" and read the Asp.net core object in my mind of the popular fish Li in the garden. To be honest, after all, I have been working for a few years, I still understand some things mentioned in the article, but I mentioned in the article:

Httprequest has a cookie attribute. msdn explains to it: "Get the set of cookies sent by the client .",This msdn explanation is not completely accurate.

Then I posted an example:

protected void Page_Load(object sender, EventArgs e){    string key = "Key1";    HttpCookie c = new HttpCookie(key, DateTime.Now.ToString());    Response.Cookies.Add(c);    HttpCookie cookie = Request.Cookies[key];    if( cookie != null )        this.labResult.Text = cookie.Value;    Response.Cookies.Remove(key);}

This example shows that request. Cookies are not only from the cookie set sent by the client, but also are affected by the modification of response. Cookies.

I have never carefully understood this in the past. I think these two are the set of cookies sent from the client, and the set of cookies that we want to output to the client, even though they are all cookies, it should be unrelated, but there is such an association, which leads to a disruption to me: Are these two sets referencing the same instance ?!

 

Request. Cookies and response. Cookies are two identities of the same person?

Why is this assumption good because it can explain the above results, but is it true? I also did the experiment:

protected void Page_Load(object sender, EventArgs e){    HttpCookieCollection hccRequest = Request.Cookies;    HttpCookieCollection hccResponse = Response.Cookies;    string key = "Key1";    HttpCookie c = new HttpCookie(key, "1");    hccResponse.Add(c);    hccResponse.Remove(key);    String key2 = "key2";    HttpCookie cookie = new HttpCookie(key2,"2");    hccRequest.Add(cookie);}

 

The code is relatively simple. Then F5 and F10 can be debugged in one step to view monitoring information.

When the first two lines of code are executed, the following tests are performed in the real-time window:

As a result, I was a little disappointed. The two are not the same thing.

Don't be discouraged, continue to execute. The monitoring information after each step will not be posted here. If you are interested, try it yourself. The result is as follows:The addition and deletion of response. Cookies will be reflected in request. cookies in a timely manner. However, response. cookies do not respond to the addition of request. Cookies.

The conclusion is as follows:The two are two instances.But why does response. Cookies affect request. Cookies ?!

 

Why does response. Cookies affect request. Cookies?

Next, we need to use. Net reflector.

Let's take a look at the request. Cookies code:

public HttpCookieCollection Cookies{    get    {        if (this._cookies == null)        {            this._cookies = new HttpCookieCollection(null, false);            if (this._wr != null)            {                this.FillInCookiesCollection(this._cookies, true);            }        }        if (this._flags[4])        {            this._flags.Clear(4);            this.ValidateCookieCollection(this._cookies);        }        return this._cookies;    }}

 

In httprequest, the private variable corresponding to _ cookies. before further discussing this code, let's take a look at the response. Cookies code:

public HttpCookieCollection Cookies{    get    {        if (this._cookies == null)        {            this._cookies = new HttpCookieCollection(this, false);        }        return this._cookies;    }}

 

In httpresponse, it is also a private variable corresponding to _ cookies. However, from the two codes, we have determined that they are not the same person,They all initialize themselves through the new httpcookiecollection and create a new instance.

Next, let's take a look at their instantiated constructors:

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

 

The key lies in the first parameter, which requires an httpresponse instance. It is appropriate to pass in your own response when response. Cookies are instantiated, but request. Cookies are passed in null.

 

Why is it critical? Next, let's take a look at the add operation of httpcookiecollection:

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

At this time, we can determine some things, because the request. cookies pass in null. For this code, only addcookie is executed, and the actual code only adds a cookie item. for response. cookies, and also perform beforecookiecollectionchange and oncookieadd operations, focusing on oncookieadd:

internal void OnCookieAdd(HttpCookie cookie){    this.Request.AddResponseCookie(cookie);}

 

The request's addresponsecookie operation was executed:

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

 

In this operation, the _ cookies are modified. From the above, we know that the request. Cookies are referenced in the request. Therefore, the code is explained here:The addition and deletion of response. Cookies will be reflected in request. cookies in a timely manner. However, response. cookies do not respond to the addition of request. Cookies.

 

In addition, we can see the fillincookiescollection (this. _ cookies, true) operation in the request. The code is too long, and only the declaration is pasted:

internal void FillInCookiesCollection(HttpCookieCollection cookieCollection, bool includeResponse)

 

This operation is to fill the request from the cookie information sent from the client. cookies set. Check whether the second parameter bool includeresponse contains response. If the input parameter is true, the request is not only filled. the cookie set is also filled with response. cookie set, which explains: The two unoperated sets we get each time always contain the same value, even though they are two different instances.

 

Correction: Sorry, I did an experiment later and found that the request. Cookies set was not filled with the response. Cookies set. Paste a piece of code that uses javasderesponse for fillincookiescollection:

if (includeResponse && (this.Response != null))        {            HttpCookieCollection cookies = this.Response.Cookies;            if (cookies.Count > 0)            {                HttpCookie[] dest = new HttpCookie[cookies.Count];                cookies.CopyTo(dest, 0);                for (int i = 0; i < dest.Length; i++)                {                    cookieCollection.AddCookie(dest[i], true);                }            }        }

In fact, the role of includeresponse is to fill in the request. Cookies set, whether to fill the data in the response. Cookies set into the request. Cookies set. This code is used to fill the data in the response. Cookies set into the request. Cookies set. In this way, response. Cookies are empty every time. Unless you take the initiative to perform the operation, you can modify the previous cookie and keep the original cookie unchanged.

 

Conclusion: request. cookies, response. cookies are two different instances. The addition and deletion operations of the two collection instances are different. cookies are added and deleted in a timely manner. cookies, for request. cookie addition and deletion operations, response. cookies do not respond (but because the values corresponding to the same key are of the reference type, modifications to these values will affect each other ).

 

Doubt

Although I understand the truth, I have more questions: why is this design necessary? Why do we need to synchronize response later. cookies are added to the request. what is the significance of cookies? The cookie to be output actually affects the cookie set sent by the request. Instead, the "request. cookies are the set of cookies sent by the client. "The explanation is inaccurate.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.