Search code examples
c#.nethttpwebrequestrestsharp

Restsharp. How to get the response details


So, in a <TargetFramework>net6.0</TargetFramework> console app, I'm using RestSharp and trying to get the error message from a PATCH request. This is what Postman returns:

Postman response

However, I can't figure out how to get this message in my C# code:

static RestResponse createOrUpdateElement(RestClient client, RestRequest request, string urlSuffix)
{
    RestResponse response = new RestResponse();
    RestResponse responsep = new RestResponse(); client.Get(request);

    client.Options.ThrowOnAnyError = true;

    try
    {
        
        response = client.Get(request);
        
        if (response.IsSuccessStatusCode)
        {
            // If the call was successful, update the record's status to "Synchronized"
            var existing = JsonSerializer.Deserialize<JsonElement>(response.Content);
            if (existing.TryGetProperty("value", out JsonElement value))
            {
                if (value.GetArrayLength() == 0)
                {
                    client = GetRestClient(urlSuffix);
                    response = client.Post(request);

                }
                //HERE I MAKE THE PATCH REQUEST 
                else
                {
                    JsonSerializer.Deserialize<JsonElement>(value[0]).TryGetProperty("SystemId", out JsonElement systemId);
                    request.AddHeader("If-Match", "*");
                    client = GetRestClient(urlSuffix + "(" + systemId.ToString() + ")");
                    responsep = client.Patch(request);
                }
            }
        }
    }

    catch (Exception ex)
    {
        responsep.ResponseStatus = ResponseStatus.Error;
        responsep.ErrorMessage = ex.Message;
        responsep.ErrorException = ex;
    }

    return response;
}

This is what I get in when debugging:

C# Response

Also tried with Execute, but I get the same Exception (BadRequest), I can't figure out how to get the 400 error I get in Postman:

//responsep = client.Patch(request);
request.Method = Method.Patch;           
responsep = client.Execute(request);

This is what I have, if I don't use try and catch:

No try/catch


Solution

  • Get it from here:

    catch (HttpException ex)
    {
        if (ex.Response != null)
        {
            // Check those values
            string statusDescription = ex.Response.StatusDescription;
            string errorMessage = ex.Response.Content;
        }
    }
    

    or you can set client.Options.ThrowOnAnyError = false; set request.Method = Method.Post; and use execute instead of patch response = client.Execute(request); to read response details from response object