zoukankan      html  css  js  c++  java
  • Post,GET中文传值乱码问题

    正常情况下,url传值前对中文进行编码,然后接受页面作对应的解码。

    即使不对含有中文的url编码,接受页面也能正确获取参数值,因为默认编码为utf-8。(POST传值包含中文也正常)

    项目中有时webconfig设置<globalization requestEncoding="gb2312"/>,或者页面上设置gb2312编码方式,若编码与解码不统一,很容易造成乱码的问题。

    utf-8编码

    GET传值:

    Request.QueryString在获取时使用gb2312解码,导致出现乱码。

    解决方法:

    Request.RawUrl 获取原url地址(未使用gb2312解码前),然后使用utf-8解码.

    Request.Url.Query 获取原url地址参数信息(未使用gb2312解码前),同上。

    POST传值:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
    </head>
    <body>
    <form action="WebForm1.aspx" method="post">
        <input type="text" name="username" />
        <br />
        <input type="text" name="address" />
        <input type="submit" />
        <br />
        <br />
        <a href="WebForm1.aspx?username=测试&&address=1">跳转</a>
    </form>
    </body>
    </html>

     WebForm1代码

     protected void Page_Load(object sender, EventArgs e)
            {
                string username = Request.Form["username"];
                string address = Request.Form["address"];
                Response.Write("username :" + username + "<br/>");
                Response.Write("address :" + address + "<br/>");
                Response.Write("<hr/>");
                Response.Write("Request.ContentEncoding.EncodingName :" + Request.ContentEncoding.EncodingName + "<br/>");
                //注意长度
                  Response.Write("Request.ContentLength :" + Request.ContentLength);
                Response.Write("<hr/>");
                //GET传值内容长度为0
                if (Request.ContentLength != 0)
                {
                    byte[] bytes = new byte[Request.InputStream.Length];
                    Request.InputStream.Read(bytes, 0, bytes.Length);
                    string input = System.Text.Encoding.Default.GetString(bytes);
    Response.Write("Request.InputStream :" + input + "<br/>"); //获取键值 string[] param = input.Split('&'); System.Collections.Generic.Dictionary<string, string> dic = new Dictionary<string, string>(); foreach (string s in param) { dic.Add(s.Split('=')[0], HttpUtility.UrlDecode(s.Split('=')[1])); } foreach (var s in dic.Keys) { Response.Write(string.Format("{0} :{1}<br/>", s, dic[s])); } } }

    输出:

  • 相关阅读:
    [MS POST]Visual Studio Tips and Tricks
    Mono
    网络编程 socket编程
    Project Properties
    Review Error Handling
    [ILDASM Boxing]从进一步了解Struct和Class的不同学到的
    Steps to Bind VS solution to Source Control
    不已0开头的数字正则
    Jquery 解决移动端onclick事件300ms延迟问题
    毫秒转换日期
  • 原文地址:https://www.cnblogs.com/goahead777/p/2683767.html
Copyright © 2011-2022 走看看