Anyone know what is up with HttpClient failing Post request?
I am making a post request to a cloudflare ai worker and HttpClient can't seem to succeed. I tried other rest clients, javascript,python and including RestSharp and it works.
Here is the code:
12 Replies
Well, what's the error?
There are a few bits of suboptimal httpclient usage in here, but that shouldn't affect the issue
error is just a 400 status code and some json schema validation failing on the cloudflare side:
{"errors":[{"message":"AiError: Bad input: must be string, must have required property 'image', must be number, must match exactly one schema in oneOf","code":5006}],"success":false,"result":{},"messages":[]}
same request works everywhere else. Something with the underlying httpclient request pipeline if I had to guess, but haven't been able to figure it out:
Here is the same request with RestSharp:
use same headers for HttpClient where you used for RestClient then
in these cases what i would do is examine the differences between a request that works and the one that doesn't with fiddler or wireshark or what have you
serialized payload looks same, only difference is headers
I'm not big on Restsharp but I ran these against a mock server
Restsharp
HttpClient
Maybe that already helps. Not sure how strict your endpoint is on certain headers
On a side note, https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests#issues-with-the-original-httpclient-class-available-in-net this should contain some good information to improve the httpclient usage pattern
Use IHttpClientFactory to implement resilient HTTP requests - .NET
Learn how to use IHttpClientFactory, available since .NET Core 2.1, for creating
HttpClient
instances, making it easy for you to use it in your applications.Thank you, so it just looks like the HttpClient doesn't have the necessary headers. This is a cloudflare Rest API endpoint btw, so it seems like they are really strict. I just don't understand why HttpClient wouldn't have all the default headers and every other program does(python, js, thunderclient(rest client)).
if I had to guess, it's gotta be the Accept-encoding header. I'll check that out.
It turned out to be the charset=utf-8.... I spent hours on this and did not expect the default content-type application/json that comes with charset=utf-8 to be the issue... sigh I even set the encoding to null on the StringContent object...
closing now. Thank you all.
Yep, Content-Type for your request, Accept Headers for what you accept as a response from the server