Search code examples
c#.netjson.netdotnet-httpclienthttpresponsemessage

.Net HttpResponseMessage.Content.ReadAsAsync<Result<TResponse>> getting null always in the TResponse value


When I do the request using Postman I get:

enter image description here

This is what I am expecting:

public class Result<TResultType>
{
    public int? ErrorId { get; protected set; } // Todo: Use it!!!
    public bool Success { get; protected set; }
    public ResponseErrorType ErrorType { get; protected set; }
    public string Message { get; protected set; }
    public TResultType Data { get; protected set; }
}

In this case, TResultType is:

public class SettingsResponse : BaseResponse
{
    public string LocationCode { get; set; }
    public string Ip { get; set; }
    public int Port { get; set; }
    public string ApplicationPrinterName { get; set; }
    public string MerchantNumber { get; set; }
    public string MessageControl { get; set; }
    public string PRIN { get; set; }
    public string SoftwareName { get; set; }
    public string SoftwareVersion { get; set; }
    public string SystemNumber { get; set; }
}

This is how I'm doing the request:

using (HttpClient client = GetHttpClient())
{
    var responseTask = client.GetAsync($"{url}/{paramsStr}");
    if (await Task.WhenAny(responseTask, Task.Delay(TimeoutSeconds * 1000)) == responseTask)
    {
        var response = await responseTask;
        return response.IsSuccessStatusCode
            ? await response.Content.ReadAsAsync<Result<TResponse>>()
            : default(Result<TResponse>);
    }

    return Result<TResponse>.FromTimeout();
}

I'm always getting null in the property Data, even when the values are there in the json response.


Solution

  • Result class with public setters in properties

    public class Result<TResultType>
    {
        public int? ErrorId { get; set; } // Todo: Use it!!!
        public bool Success { get; set; }
        public ResponseErrorType ErrorType { get; set; }
        public string Message { get; set; }
        public TResultType Data { get; set; }
    }
    

    It is working now.