我的 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 为空,而不是包含我在客户端代码中使用此行分配的 guid 字符串
var deviceAccessResponse = new DeviceAccessResponse(deviceAccessRequest.RequestId)
我错过了什么?
是response.Content.ReadAsAsync<DeviceAccessResponse>().Result;
用来重建我的整个对象的正确代码吗?