使用HttpListener搭建http服务器时,使用HttpListenerRequest.ContentEncoding获取客户端Post的内容的编码。
但实际上获取不到。
msdn对HttpListenerRequest.ContentEncoding值的解释是:
This property uses the charset value from the Content-Type header to determine the encoding. If that information is not available, this property returnsEncoding.Default.
查看Request的Header的Content-Type属性,会发现根本没有charset信息,因而ContentEncoding属性返回的总是Encoding.Default。如果客户端页面的charset设置,正好与Encoding.Default一样,那不会有问题,否则,会乱码。
解决的方法是,服务器和客户端约定使用同一个编码(找不到把encoding信息嵌入到http header的content-type字段的方法)。
比如,约定使用utf-8,则客户端的html页面定义如下
-------------------------------------
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8" />
...
-------------------------------------
服务器端不要使用HttpListenerRequest.ContentEncoding,直接使用Encoding.Utf8来解码数据,就不会有错。
HttpListenerRequest.ContentEncoding
原文:http://www.cnblogs.com/erentec/p/5165704.html