7.8. 解析Cookie的项和域值:parseCookieField


    // parse cookie field expression
    public bool parseCookieField(string ckFieldExpr, out pairItem pair)
    {
        bool parsedOK = false;

        if (ckFieldExpr == "")
        {
            pair.key = "";
            pair.value = "";
            parsedOK = false;
        }
        else
        {
            ckFieldExpr = ckFieldExpr.Trim();

            //some specials: secure/httponly
            if (ckFieldExpr.ToLower() == "httponly")
            {
                pair.key = "httponly";
                //pair.value = "";
                pair.value = "true";
                parsedOK = true;
            }
            else if (ckFieldExpr.ToLower() == "secure")
            {
                pair.key = "secure";
                //pair.value = "";
                pair.value = "true";
                parsedOK = true;
            }
            else // normal cookie field
            {
                int equalPos = ckFieldExpr.IndexOf('=');
                if (equalPos > 0) // is valid expression
                {
                    pair.key = ckFieldExpr.Substring(0, equalPos);
                    pair.key = pair.key.Trim();
                    if (isValidCookieField(pair.key))
                    {
                        // only process while is valid cookie field
                        pair.value = ckFieldExpr.Substring(equalPos + 1);
                        pair.value = pair.value.Trim();
                        parsedOK = true;
                    }
                    else
                    {
                        pair.key = "";
                        pair.value = "";
                        parsedOK = false;
                    }
                }
                else
                {
                    pair.key = "";
                    pair.value = "";
                    parsedOK = false;
                }
            }
        }

        return parsedOK;
    }//parseCookieField

    

例 7.8. parseCookieField 的使用范例


    foreach (string eachExpression in fieldExpressions)
    {
        //parse key and value
        if (parseCookieField(eachExpression, out pair))
        {
            // add to cookie field if possible
            addFieldToCookie(ref ck, pair);
        }
        else
        {
            // if any field fail, consider it is a abnormal cookie string, so quit with false
            parsedOk = false;
            break;
        }
    }