HttpClient method returning a stream
I have created a class with a method to send httpclient requests to an api. The method returns the result as a stream. I return a stream because I need to deserialise the stream multiple times, and with different objects depending on the api.
I feel that it might be incorrect to return a stream. Would it be better if I returned a class with a stream property and a dispose method that disposes the stream? I then wouldn't require a using statement to dispose the stream?
Thanks.
Edit:
The method takes in the http method, url, content and headers and returns a response stream. I then need to deserialise to check for the error status, and if there are no errors I stream into the full response object. Unfortunately, the api returns a 200 even with errors so I have to check for errors first.
Depending on the scenario, I have to deserialse to different response objects.
Posted Nov 11, 2021, 2:28 AM UTC · edited
I appreciate that you might not have control over this, but if the API response contains errors, it should ideally be returning an HTTP status code that indicates that the call was unsuccessful and/or setting the content type on the response to indicate that it contains error information (such as an RFC 7807 problem details object) rather than the expected response content.
I agree. I've recently had to call apis from two different companies and they both return a 200 on error. It's a bit frustrating :).
You have my sympathies! If the responses are JSON, you could always try deserializing the response as a
JsonElement, examining it to see if it contains the properties that indicate it is an error response, and then either deserializing theJsonElementto the actual type you were expecting or extracting and throwing the error information?EDIT
Here's an example of what I mean:
Thanks wazzamatazz.