【问题标题】:Why can I not save UTF-8 characters to my database?为什么我不能将 UTF-8 字符保存到我的数据库中?
【发布时间】:2017-06-14 22:50:32
【问题描述】:

我正在从事一个非常大的公司项目。它是一个 C#、.NET 实体框架站点,其背后有一个 Microsoft SQL 服务器。

我正在测试的输入在这样的表单中:

@using (Html.BeginForm("CreateAgency", "Agency", FormMethod.Post, new { enctype = "multipart/form-data", accept_charset = "utf-8" }))
{
...
<li>
<label id="lblAgency" class="AgencyEditorPanelItemsLabel">Agency Name</label>
@Html.TextBoxFor(m => m.AgencyName, new { @class="newAgencyTextInput"})
</li>
...

这会返回到 AgencyController 进行解析:

NameValueCollection nvc = HttpUtility.ParseQueryString(String.Empty);
nvc.Add("AgencyName", agency.AgencyName);
...

然后它被打包成一个字符串以通过 API 发布:

//make the post object readily convertable to a string
StringBuilder sb = new StringBuilder();
sb.Append(nvc.ToString());
//encode collection for pending transmission
var data = Encoding.UTF8.GetBytes(sb.ToString());

我所展示的代码中是否有任何内容会导致 UTF-8 字符变成 "%u00a5 %u00b7 %u00a3 %u00b7 %u20ac %u00b7 $ %u00b7 %u00a2 %u00b7 %u20a1 %u00b7 %u20a2 %u00b7 %u20a3 “?我什至尝试向我的 webconfig 添加一个全球化密钥,如下所示:

<globalization fileEncoding="utf-8" requestEncoding="utf-8" responseEncoding="utf-8" />

但这并没有起到任何作用。有没有人有一些我可以尝试解决此问题的提示或想法?

非常感谢您的帮助!

【问题讨论】:

  • 向我们展示您用于将字符串写入数据库的代码。此外,应该不需要 Encoding.UTF8.GetBytes(sb.ToString()); - ADO.NET 和 SQL Server 知道如何处理字符串和 nvarchar - 您可以直接保存值,而无需将其转换为字节数组。
  • 好的,在追踪变量之后,我已经确定在这两行字符中断:NameValueCollection nvc = HttpUtility.ParseQueryString(String.Empty); nvc.Add("AgencyName", agency.AgencyName);这里一定有问题,但是什么?
  • 看起来这与我刚刚发现的这个问题相似:ParseQueryString always encodes special characters to unicode
  • 你为什么使用 nvc ?您不应该尝试将 nvc(或 nvc.ToString())插入数据库。该变量/代码/概念用于读取/写入查询字符串,而不是数据库。与我们讨论您尝试使用 ParseQueryString 和 nvc 变量解决的问题。
  • 请原谅我可怜的 C# 技能,但如果我在 PowerShell 中模拟你的 .NET 代码,那么 $nvc.ToString() 包含 %u00a5%u00b7%u00a3%u00b7%u20ac%u00b7%24%u00b7%u00a2%u00b7%u20a1%u00b7%u20a2%u00b7%u20a3 即 Unicode 字符的非标准编码为 %uxxxx。但是,$nvc['Agencyname'] 返回¥·£·€·$·¢·₡·₢·₣。 HTH。

标签: c# .net encoding utf-8 localization


【解决方案1】:

为了其他有类似问题的人的利益,事实证明服务器正在使用 %s 作为 URI 对其进行编码。由于我们不需要该功能,因此我在 web.config 文件中添加了以下内容:

<appSettings>
<add key="aspnet:DontUsePercentUUrlEncoding" value="true" />

这会停止自动 URL 编码,因此如果您需要该功能,请不要忘记手动对需要它的 URL 进行编码。

【讨论】:

    猜你喜欢
    • 2016-04-19
    • 2022-01-18
    • 2012-07-05
    • 1970-01-01
    • 2023-03-18
    • 2012-12-19
    • 1970-01-01
    • 2016-05-07
    • 2018-03-08
    相关资源
    最近更新 更多