Repository navigation
Best Practices for Working with Stream Responses? #1525
|
I have a few endpoints that return Let's say I have some interface: public interface ISignature
{
[Get("/signature")]
Task<IApiResponse<byte[]>> GetDoc();
}When I attempt to run tests with this client, I run into a few snags. /* As part of a [Test] method */
var response = await _api.GetDoc();
Assert.That(response.IsSuccessStatusCode);
/* This fails, even though the endpoint is working exactly as expected */
Assert.That(response.Error, Is.Null);I can execute the request, but Refit (by default) tries to deserialize the response into JSON, which of course does not work. Of course, I came across this older issue, but I wanted to see if this was still up to date. What are the recommendations for telling Refit that the response body should not be parsed as JSON? |
Replies: 1 comment
|
For raw binary responses use one of the types Refit treats as raw content:
Examples: [Get("/signature")]
Task<Stream> GetDoc();
// keep status/headers access:
[Get("/signature")]
Task<IApiResponse<HttpResponseMessage>> GetDoc();With await using var s = await api.GetDoc();
using var ms = new MemoryStream();
await s.CopyToAsync(ms);
var bytes = ms.ToArray();If you specifically need Raw-content handling is in DeserializeContentAsync in RequestBuilderImplementation.cs (it special-cases |
byte[]is not special-cased on the response path, so Refit hands the body to the JSON serializer, which is why a raw binary body fails to "deserialize".For raw binary responses use one of the types Refit treats as raw content:
StreamHttpResponseMessageHttpContentExamples:
With
Streamyou read the bytes yourself:If you specifically need
byte[], plug in a content serializer that returns the raw bytes for that type, or…