Server.UrlEncode()指定GBK编码

问题:Server.UrlEncode(“你好”) 无法指定编码格式

解决方法:
方法一、调用Server.UrlEncode()之前加入
Response.ContentEncoding = System.Text.Encoding.GetEncoding(“GBK”)
方法二、在web.config中配置:

<configuration>
 <system.web>
  <globalization requestEncoding="GBK" responseEncoding="GBK" />
 system.web>
configuration>

原因:

查看Server.UrlEncode()源码 (HttpServerUtility类):

public string UrlEncode(string s) {
    Encoding e = (_context != null) ? _context.Response.ContentEncoding : Encoding.UTF8;
    return HttpUtility.UrlEncode(s, e);
}

而_context.Response.ContentEncoding的源码为

public Encoding ContentEncoding {
    get {
        if (_encoding == null) {
        // use LKG config because Response.ContentEncoding is need to display [config] error
            GlobalizationSection globConfig = RuntimeConfig.GetLKGConfig(_context).Globalization;
            if (globConfig != null)
                _encoding = globConfig.ResponseEncoding;

            if (_encoding == null)
                _encoding = Encoding.Default;
        }

        return _encoding;
    }
    set {
        if (value == null)
            throw new ArgumentNullException("value");

        if (_encoding == null || !_encoding.Equals(value)) {
            _encoding = value;
            _encoder = null;   // flush cached encoder

            if (_httpWriter != null)
                _httpWriter.UpdateResponseEncoding();
        }
    }
}

一目了然

你可能感兴趣的:(.NET)