Gor*_*son 3 asp.net encoding utf-8 iso-8859-1
我们有一个页面将数据发布到ISO-8859-1中的ASP.NET应用程序
<head>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<title>`Sample Search Invoker`</title>
</head>
<body>
<form name="advancedform" method="post" action="SearchResults.aspx">
<input class="field" name="SearchTextBox" type="text" />
<input class="button" name="search" type="submit" value="Search >" />
</form>
Run Code Online (Sandbox Code Playgroud)
并在后面的代码(SearchResults.aspx.cs)
System.Collections.Specialized.NameValueCollection postedValues = Request.Form;
String nextKey;
for (int i = 0; i < postedValues.AllKeys.Length; i++)
{
nextKey = postedValues.AllKeys[i];
if (nextKey.Substring(0, 2) != "__")
{
// Get basic search text
if (nextKey.EndsWith(XAEConstants.CONTROL_SearchTextBox))
{
// Get search text value
String sSentSearchText = postedValues[i];
System.Text.Encoding iso88591 = System.Text.Encoding.GetEncoding("iso-8859-1");
System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
byte[] abInput = iso88591.GetBytes(sSentSearchText);
sSentSearchText = utf8.GetString(System.Text.Encoding.Convert(iso88591, utf8, abInput));
this.SearchText = sSentSearchText.Replace('<', ' ').Replace('>',' ');
this.PreviousSearchText.Value = this.SearchText;
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我们通过Merkblätter时,它会被postValues [i]拉出来作为Merkbl tter原始字符串是Merkbl%ufffdtter
有任何想法吗?
你有这行代码: -
String sSentSearchText = postedValues[i];
Run Code Online (Sandbox Code Playgroud)
这里发生了对帖子中八位字节的解码.
问题是META http-equiv不告诉服务器有关编码的信息.
您可以将RequestEncoding ="ISO-8859-1"添加到@Page指令中,并停止尝试自己解码(因为它已经发生).
这也无济于事.看来你只能在web.config中指定Request encoding.
最好是完全停止使用ISO-8859-1,并保留默认的UTF-8编码.我看到使用限制性编码没有任何好处和痛苦.
编辑
如果看起来不太可能改变发布形式编码,那么我们似乎只能自己处理解码.为此,在接收代码隐藏中包含这两种静态方法: -
private static NameValueCollection GetEncodedForm(System.IO.Stream stream, Encoding encoding)
{
System.IO.StreamReader reader = new System.IO.StreamReader(stream, Encoding.ASCII);
return GetEncodedForm(reader.ReadToEnd(), encoding);
}
private static NameValueCollection GetEncodedForm(string urlEncoded, Encoding encoding)
{
NameValueCollection form = new NameValueCollection();
string[] pairs = urlEncoded.Split("&".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
foreach (string pair in pairs)
{
string[] pairItems = pair.Split("=".ToCharArray(), 2, StringSplitOptions.RemoveEmptyEntries);
string name = HttpUtility.UrlDecode(pairItems[0], encoding);
string value = (pairItems.Length > 1) ? HttpUtility.UrlDecode(pairItems[1], encoding) : null;
form.Add(name, value);
}
return form;
}
Run Code Online (Sandbox Code Playgroud)
现在而不是分配: -
postedValues = Request.Form;
Run Code Online (Sandbox Code Playgroud)
使用:-
postValues = GetEncodedForm(Request.InputStream, Encoding.GetEncoding("ISO-8859-1"));
Run Code Online (Sandbox Code Playgroud)
您现在可以从其余代码中删除编码marlarky.
| 归档时间: |
|
| 查看次数: |
17791 次 |
| 最近记录: |