size limit workaround for FormUrlEncodedContent

后端 未结 2 672
执念已碎
执念已碎 2021-01-19 06:20

I\'m receiving the error:

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

The problem is with this line:



        
2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-19 06:34

    Let's adapt your existing code to the solution in this post

    int limit = 2000;
    
    StringContent content = new StringContent(postData.Aggregate(new StringBuilder(), (sb, nxt) => {
    
        StringBuilder sbInternal = new StringBuilder();
    
        if (sb.Length > 0)
        {
            sb.Append("&");
        }
    
        int loops = nxt.Value.Length / limit;
    
        for (int i = 0; i <= loops; i++)
        {
            if (i < loops)
            {
                sbInternal.Append(Uri.EscapeDataString(nxt.Value.Substring(limit * i, limit)));
            }
            else
            {
                sbInternal.Append(Uri.EscapeDataString(nxt.Value.Substring(limit * i)));
            }
        }
    
        return sb.Append(nxt.Key + "=" + sbInternal.ToString());
    }).ToString(), Encoding.UTF8, "application/x-www-form-urlencoded");
    

    Quick walkthrough that code: Implode each key-value pair (parameter) in your dictionary with LINQ's Aggregate using a limit-proof URL encoding method.

    The length of string parameter of Uri.EscapteDataString method is limited to 32766 characters, the limit local property must be 32766 to avoid unnecessary iteration.

    This is how you should create you content now, instead of using FormUrlEncodedContent

    Hopefully it'll help.

提交回复
热议问题