Search code examples
c#jsonrestsharp

RestSharp deserializing 401 response to object with default values


I've experienced an issue while using RestSharp.

I have a method in my client which is show below. When I send a request with a valid token I get an IEnumerable of type StravaActivityDto, and its working fine. But when I send a request and my token is not valid, instead of activities variable being null it is IEnumerable of type StravaActivityDto, but it always has only one object in it and this has a default value in every property (e.g. Id=0, MaxSpeed=0).

object

I have checked the behavior in Postman and if I make a request with an invalid token the status code of the response is 401.

How can I stop RestSharp from deserializing the response if the request is invalid (which results in creating StravaActivityDto with default values).
I know I can use request.Execute and then check IsSuccessful status but I would like to just get null after calling request.Get<>().

public async Task<IEnumerable<StravaActivityDto>> GetActivities(string token)
{
    var request = new RestRequest("activities", DataFormat.Json);
    request.AddHeader("authorization", "Bearer " + token);
    var activities = await RestClient.GetAsync<IEnumerable<StravaActivityDto>>(request);

    return activities;
}

Solution

  • This is default behavior of RestSharp, it didn't throw any errors on responses with HTTP errors, only on transport level (when server is unreachable or etc)

    So you have 2 options:

    First

    Add OnBeforeDeserialization on every request

    request.OnBeforeDeserialization = response =>
    {
         if (!response.IsSuccessful)
              throw new Exception("Response is unsuccessful");
    };
    

    Second

    Use ExecuteGetAsync instead of GetAsync method and check for errors on every response.

    var response = await client.ExecuteGetAsync<IEnumerable<StravaActivityDto>>(request);
                    
    if (!response.IsSuccessful)
        throw new Exception("Response is unsuccessful");
    
    return response.Data;
    

    also instead of using

    request.AddHeader("authorization", "Bearer " + token);
    

    on every requests, you can use JwtAuthenticator (or your custom authenticator if you want) once in client initialization.

    var client = new RestClient()
    {
        Authenticator = new JwtAuthenticator("MyBearerToken")
    };