Damn Vegetables
Damn Vegetables

Reputation: 12474

FormUrlEncodedContent's length limitation, MS's arbitary decision or HTTP specification?

I got "Invalid URI: The Uri string is too long." at new FormUrlEncodedContent(pair);. After some web searching, I found that there is about 2000 length limitation. The user mentioned that a URL has a size limitation, and I think it makes sense that a URL should not be too long like more than 2000 characters. But, in my case, I am not trying to use that as a URL of a GET request; I am trying to encode the form data into the body of a POST request. So, the 2000 limitation seems too short.

I searched the web for "x-www-form-urlencoded maximum length", but I could not find the answer. Nor do the documentation page or the source code mention about the length limitation.

Since I am calling a REST API, I cannot change the server. So, the question is, should the length of the body of a "x-www-form-urlencoded" POST request be limited to about 2000 as Microsoft has implemented? Or can I ignore it and put longer data? If it is the former, I could break down the request into multiple requests, but if it is the latter, do I have to manually encode the string as existing answers showed, or is there an existing official class for this kind of task?

Upvotes: 2

Views: 714

Answers (1)

Todd Menier
Todd Menier

Reputation: 39329

The actual limitation is (was?) 65,520 characters. There is a bit of history about it here. Interestingly, it appears this limit was finally removed in .NET Core just recently (10/10/2019).

As of this writing, I am not certain whether that change is yet available in the latest stable release of .NET Core, but suffice to say that the reasons for the limitation in the first place are very "legacy" (not based on any current spec), it may never be removed in .NET Framework, and it has been removed in .NET Core.

If you need to target other/older platforms, one alternative is to use Flurl (disclaimer: I'm the author). Its PostUrlEncodedAsync method offers a much cleaner syntax and uses encoding methods designed to work around this limit and other quirks.

await "http://example.com".PostUrlEncodedAsync(new { 
    data1 = "value1", 
    data2 = "value2"
});

Upvotes: 2

Related Questions