c# - Uri.EscapeDataString() - 无效的 URI : The Uri string is too long

标签 c# exception-handling httpwebrequest compact-framework uri

我在 Windows Mobile 上使用紧凑型框架/C#。

在我的应用程序中,我通过序列化对象并使用 HttpWebRequest/POST 请求向上发送信息来将数据上传到服务器。在服务器上,发布数据被反序列化并保存到数据库中。

前几天我意识到我在发布数据中遇到了特殊字符的问题(& 号等)。所以我将 Uri.EscapeDataString() 引入到方法中,一切都很好。

但是,今天我发现应用程序尝试上传大量数据时会出现问题(我现在不确定“大”到底是什么意思!)

现有代码(种类)

var uploadData = new List<Things>();

uploadData.Add(new Thing() { Name = "Test 01" });
uploadData.Add(new Thing() { Name = "Test 02" });
uploadData.Add(new Thing() { Name = "Test with an & Ampersand " }); // Do this a lot!!

var postData = "uploadData=" + Uri.EscapeDataString(JsonConvert.SerializeObject(uploadData, new IsoDateTimeConverter()));

问题

对 Uri.EscapeDataString() 的调用导致以下异常:

System.UriFormatException: Invalid URI: The Uri string is too long.

问题

还有其他方法可以准备上传数据吗?

据我所知,HttpUtility(它有自己的编码/解码方法)不适用于紧凑型框架。

最佳答案

或者您可以简单地拆分您的字符串并为每个 block 调用 Uri.EscapeDataString(string),以避免重新实现该函数。

示例代码:

        String value = "large string to encode";
        int limit = 2000;

        StringBuilder sb = new StringBuilder();
        int loops = value.Length / limit;

        for (int i = 0; i <= loops; i++)
        {
            if (i < loops)
            {
                sb.Append(Uri.EscapeDataString(value.Substring(limit * i, limit)));
            }
            else
            {
                sb.Append(Uri.EscapeDataString(value.Substring(limit * i)));
            }
        }

关于c# - Uri.EscapeDataString() - 无效的 URI : The Uri string is too long,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6695208/

相关文章:

javascript - 逗号插入无限小数中

c# - System.IdentityModel.Tokens 和 Microsoft.IdentityModel.Tokens 之间的冲突

php - Laravel 5 覆盖异常处理程序

ruby-on-rails - 处理不同类别的 404 错误

c# - 如何在 WP7 中处理 HttpWebRequest 的错误?

c# - HttpWebRequest 在 mono 和 .net 中的实现方式不同吗?

c# - 在 C# 中使用 Windows 应用程序执行 http 方法

c# - 无法向电子邮件发送消息

c# - LINQ 查询基于列表的子字符串进行过滤

android - 处理 Android 中未处理的异常