返回的对象的一部分为null

时间:2013-03-11 15:17:25

标签: c# .net asp.net-mvc json asp.net-web-api

我的web api控制器中有以下方法

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;
}

这是调用客户端代码:

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;

    }
}

对象类:

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;
    }
}

我能够在我的控制器中接收DeviceAccessRequest就好了,我能够获得guid字符串。

但是,在将响应返回给客户端后,我只能返回Status =“OK”,correlationId为null,而不是包含我在客户端代码中使用此行分配的guid字符串

var deviceAccessResponse = new DeviceAccessResponse(deviceAccessRequest.RequestId)

我错过了什么?

response.Content.ReadAsAsync<DeviceAccessResponse>().Result;用于重建整个对象的正确代码吗?

2 个答案:

答案 0 :(得分:3)

您的correlationId是私人字段。如果您希望它通过网络进行序列化,您可能需要创建一个公共属性来公开它。

答案 1 :(得分:1)

如果你希望公共财产被公开并送往客户,你应该将correlationId作为公共财产:

public class ResponseBase
{
    public ResponseBase()
    {
    }

    public string CorrelationId { get; set; }

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