我们有一个页面将数据发布到 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>
并在后面的代码中 (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;
}
}
}
当我们通过 Merkblätter 时,它会从 PostedValues[i] 中提取为 Merkblätter
原始字符串字符串是 Merkbl%ufffdtter
有任何想法吗?
最佳答案
你有这行代码:-
String sSentSearchText = postedValues[i];
帖子中八位字节的解码发生在这里。
问题是 META http-equiv 不会告诉服务器有关编码的信息。
您可以将 RequestEncoding="ISO-8859-1"添加到 @Page 指令中,并停止尝试自己摆弄解码(因为它已经发生了)。
那也无济于事。看来您只能在 web.config 中指定请求编码。
更好的做法是完全停止使用 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;
}
现在而不是分配:-
postedValues = Request.Form;
用:-
postValues = GetEncodedForm(Request.InputStream, Encoding.GetEncoding("ISO-8859-1"));
您现在可以从代码的其余部分中删除编码 marlarky。
关于asp.net - ASP.NET 2 中的 ISO-8859-1 到 UTF8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1012120/