canton7 / RestEase

Easy-to-use typesafe REST API client library for .NET Standard 1.1 and .NET Framework 4.5 and higher, which is simple and customisable. Inspired by Refit
MIT License
1.09k stars 109 forks source link

Content-Type Plain Text Deserialize Response #170

Open stephenstroud opened 4 years ago

stephenstroud commented 4 years ago

I'm trying to deserialise a Text/Plain response, however, found the JSON is the default. I've created the following but doesn't feel right, Isn't there an easier way? Moreover, it would be great in addition to JsonResponseDeserializer if there were more pre-made deserializer classes to pick from.


      public override T Deserialize<T>(string content, HttpResponseMessage response, ResponseDeserializerInfo info)
        {   
            if(typeof(string).IsAssignableFrom(typeof(T)))
            {
                return (T)(object)content;
            }

            throw new InvalidDataException("Plain Text response deserializer can only be used with string");
        }
canton7 commented 4 years ago

Can you add more detail on what you're trying to achieve, please?

Using an interface method which returns Task<string> will always return the raw response, without going through a deserializer.

stephenstroud commented 4 years ago

Instead I have Task<Response<string>> decorated with [AllowAnyStatusCode] As I need granular control over the response as I need to act on different Status Codes.

i.e.

  if (response.ResponseMessage.StatusCode == HttpStatusCode.Unauthorized)...

My proposed solution has worked above but good to know if there is another way.

Task<Response<string>> Does fail using the default JSON deserializer

canton7 commented 4 years ago

Can you use Response<string>.StringContent?

The fact that Response<string>.GetContent() uses the deserializer is an oversight, but I'm not sure whether I can change it safely at this point.

canton7 commented 3 years ago

I think this is probably a candidate for 2.0 -- I want to rethink handling of strings there entirely.