3

I am using RestSharp to create http requests to a webservice. One of the parameters length is very long running >100 K characters, so I figured I'll need to use the POST method (because of limitations on length of query string with GET). However, when I tried doing so I got an exception that the uri is too long. I downloaded their source code to find out why. Take a look at the following code:

querystring.AppendFormat("{0}={1}", p.Name.UrlEncode(), p.Value.UrlEncode());

Now the UrlEncode() method is an extension method available in StringExtensions.cs class and it's implementations is like so:

public static string UrlEncode(this string input)
    {
        return Uri.EscapeDataString(input);
    }

The problem is that Uri.EscapeDataString cannot process a string more than 65519 characters (see post - Uri.EscapeDataString() - Invalid URI: The Uri string is too long)

My problem can be solved if the UrlEncode extension method was implemented like this

public static string UrlEncode(this string input)
    {
        int limit = 65520;

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

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

        return sb.ToString();
    }

The issue is that I DON'T want to HAVE to modify the source code. Is there a way I can write my own extension method in MY source code such that when the third party code is trying to invoke UrlEncode() it ignores it's own extension method and instead calls my extension method??

Any help is much appreciated. Thanks.

4

3 回答 3

3

谢天谢地,我不知道有什么办法。扩展方法s.UrlEncode()基本上是语法糖

StringExtensions.UrlEncode(s);

由于此方法是静态的,因此无法“覆盖”它。此外,它在编译时绑定到该方法,因此无法在运行时将其重定向到不同的方法。

它也不应该被允许。如果是这样,您可以创建一个“覆盖”它来格式化您的 C 驱动器!

如果您想使用不同的版本,您可以创建一个具有不同名称的新扩展方法,或者想办法缩短参数长度。:)

于 2013-05-20T14:35:24.423 回答
1

一种解决方案是通过继承来扩展现有的 Uri 类- 您应该继承现有的 Uri 类,然后用new运算符覆盖所需的方法。这样您就可以在不修改原始代码的情况下更改默认行为。代码示例:

public class A
{
    public int Get1()
    {
        return 1;
    }

    public int Get2()
    {
        return 100;
    }
}

public class B : A
{
    // override A's Get1
    public new int Get1()
    {
        return 2;
    }
}

和调用的输出:

var b = new B();
System.Console.WriteLine(string.Format("{0} - {1}", b.Get1(), b.Get2()));

将会:

2 - 100

而不是 1 - 100!

希望这可以帮助。

问候,P。

于 2013-05-20T14:23:49.303 回答
1

查看此答案以了解如何POST使用 RestSharp。有效负载位于消息正文中,而不是查询字符串中。

于 2013-05-20T14:35:34.647 回答