2010年10月15日

Ajax提交时要用encodeURIComponent做编码,encodeURIComponent是UTF-8编码,
国内一般用gb2312编码,如果在web.config里定义了<globalization requestEncoding=”GB2312″ responseEncoding=”GB2312″/>
提交到asp.net程序会出现中文乱码,解决方法有以下两个:
(1)在web.config里修改接收程序的编码;
    <location path=”接收程序.aspx”>
        <system.web>
            <httpRuntime maxRequestLength=”1024″ executionTimeout=”100″  />
            <globalization requestEncoding=”utf-8″/>
        </system.web>
    </location>

(2)不修改web.config,在接收程序.aspx.cs里修改接收编码。

    protected void Page_Load(object sender, EventArgs e)
    {
        NameValueCollection paramList = GetRequestParameters(Request, “utf-8″);
        string content = paramList["content"];
        //此时再输出content就不会乱码
   }

    public static NameValueCollection GetRequestParameters(HttpRequest request, string encode)
    {
        NameValueCollection result = null;
        Encoding destEncode = null;

        //根据指定的编码格式获取Encoding对象  
        if (!String.IsNullOrEmpty(encode))
        {
            try
            {
                //获取指定的编码格式  
                destEncode = Encoding.GetEncoding(encode);
            }
            catch
            {
                //如果获取指定编码格式失败,则默认为null  
                destEncode = null;
            }
        }

        //根据不同的HttpMethod方式,获取请求的参数.  
        if (request.HttpMethod == “POST”)
        {
            if (null != destEncode)
            {
                Stream resStream = request.InputStream;
                byte[] filecontent = new byte[resStream.Length];
                resStream.Read(filecontent, 0, filecontent.Length);
                string postquery = destEncode.GetString(filecontent);
                result = HttpUtility.ParseQueryString(postquery, destEncode);
            }
            else
            {
                result = request.Form;
            }
        }
        else
        {
            if (null != destEncode)
            {
                result = System.Web.HttpUtility.ParseQueryString(request.Url.Query, destEncode);
            }
            else
            {
                result = request.QueryString;
            }
        }

        //返回结果  
        return result;
    }