您的位置:首页 > 其它

post参数解析

2012-08-28 11:21 134 查看
 #region post参数解析

    /// <summary>

    /// post参数解析

    /// </summary>

    /// <param name="s"></param>

    /// <param name="isUrlDecode"></param>

    /// <param name="encoding"></param>

    /// <returns></returns>

    private static NameValueCollection FillFromString(string s, bool isUrlDecode, Encoding encoding)

    {

        NameValueCollection parametersCollection = new NameValueCollection();

 

        // 参数字符串长度 

        int sLen = (s != null) ? s.Length : 0;

 

        // 遍历每个字符 

        for (int i = 0; i < sLen; i++)

        {

            // 参数名开始位置 

            int startIndex = i;

 

            // 参数名结束位置 

            int endIndex = -1;

 

            // 字符索引前进,直到遇到等号,更新结束的索引位置 

            // 如果遇到&符号,则参数结束,退出循环 

            while (i < sLen)

            {

                char ch = s[i];

                if (ch == '=')

                {

                    if (endIndex < 0)

                    {

                        endIndex = i;

                    }

                }

                else if (ch == '&')

                {

                    break;

                }

 

                // 字符索引前进 

                i++;

            }

 

            string parameterName = null;

            string parameterValue = null;

 

            // 存在等号,可以获取到参数名和参数值 

            if (endIndex >= 0)

            {

                parameterName = s.Substring(startIndex, endIndex - startIndex);

                parameterValue = s.Substring(endIndex + 1, (i - endIndex) - 1);

            }

            else

            {

                parameterValue = s.Substring(startIndex, i - startIndex);

            }

 

            // 需要解码 

            if (isUrlDecode)

            {

                parametersCollection.Add(HttpUtility.UrlDecode(parameterName, encoding), HttpUtility.UrlDecode(parameterValue, encoding));

            }

            else

            {

                parametersCollection.Add(parameterName, parameterValue);

            }

 

            // 最后一个字符是 &,则添加一个参数为null的NameValue对。 

            if ((i == (sLen - 1)) && (s[i] == '&'))

            {

                parametersCollection.Add(null, string.Empty);

            }

        }

 

        return parametersCollection;

    }

    #endregion
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  encoding null string