Null Reference
Null Reference

Reputation: 11340

Part of object that is returned is null

I have the following method in my web api controller

public HttpResponseMessage PostGrantAccess(DeviceAccessRequest deviceAccessRequest)
{
    var deviceId = deviceAccessRequest.DeviceId;

    var deviceAccessResponse = new DeviceAccessResponse(deviceAccessRequest.RequestId)
        {
            Status = "OK"
        };
    var response = Request.CreateResponse<DeviceAccessResponse>(HttpStatusCode.OK, deviceAccessResponse);
    return response;
}

This is the calling client code:

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://localhost:55208/");

    var request = new DeviceAccessRequest
    {
        RequestId = Guid.NewGuid().ToString(),
        DeviceId = "bla",
        LoginId = "tester",
        Password = "haha" ,                    
    };
    var response = client.PostAsJsonAsync("api/accesspanel", request).Result;
    if (response.IsSuccessStatusCode)
    {
        var deviceAccessResponse = response.Content.ReadAsAsync<DeviceAccessResponse>().Result;

    }
}

Object classes:

public class DeviceAccessResponse : ResponseBase
{
    public DeviceAccessResponse()
    {
    }

    public DeviceAccessResponse(string correlationId)
        : base(correlationId)
    {
    }

    public string Status { get; set; }
}

public class ResponseBase
{
    private string correlationId;

    public ResponseBase()
    {
    }

    public ResponseBase(string correlationId)
    {
        this.correlationId = correlationId;
    }
}

I am able to receive DeviceAccessRequest in my controller just fine, I am able to get the guid string.

However, after returning the response back to the client, I am only able to get back Status = "OK", the correlationId is null instead of containing the guid string which I have assigned in the client code with this line

var deviceAccessResponse = new DeviceAccessResponse(deviceAccessRequest.RequestId)

What did I miss?

is the response.Content.ReadAsAsync<DeviceAccessResponse>().Result; the correct code to use to reconstruct my whole object?

Upvotes: 0

Views: 383

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

You should make the correlationId a public property if you want it to be exposed and travel to the client:

public class ResponseBase
{
    public ResponseBase()
    {
    }

    public string CorrelationId { get; set; }

    public ResponseBase(string correlationId)
    {
        this.CorrelationId = correlationId;
    }
}

Upvotes: 1

Dan Puzey
Dan Puzey

Reputation: 34198

Your correlationId is a private field. If you want it to serialize over the wire, you probably need to make a public property to expose it.

Upvotes: 3

Related Questions