空对象无法转换为值类型

Rom*_*meo 5 c# asp.net-mvc json asp.net-mvc-4 asp.net-web-api

我根据用户提供的预订编号从我的 ASP.NET Web API 请求预订信息。我的问题是,如果预订号不存在,Web API 仍会返回一个对象,但值为null. 如何检查返回的 JSON 对象是否为null

HttpClient 要求:

 var response = await client.PostAsJsonAsync(strRequestUri, value);

if (response.IsSuccessStatusCode)
{
    string jsonMessage;
    using (Stream responseStream = await response.Content.ReadAsStreamAsync()) // put response content to stream
    {
        jsonMessage = new StreamReader(responseStream).ReadToEnd(); 
    }
    // I'm getting the error from here when I'm casting the json object to my return type.
    return (TOutput)JsonConvert.DeserializeObject(jsonMessage, typeof(TOutput)); // TOutput is a generic object
}
Run Code Online (Sandbox Code Playgroud)

示例返回的 JSON 对象:

{
    "BookingRef": null,
    "City": null,
    "Company": null,
    "Country": null,
    "CustomerAddress": null,
    "CustomerFirstName": null,
    "CustomerPhoneNumber": null,
    "CustomerSurname": null,
    "Entrance": null
}
Run Code Online (Sandbox Code Playgroud)

Lar*_*ann 2

一种选择是对属性使用后期绑定:

var result = JsonConvert.DeserializeObject(jsonMessage, typeof(TOutput));
if (((dynamic)result).BookingRef == null)
{
    // Returning null - do whatever is appropriate
    return null;
}
else
{
    return (TOutput)result;
}
Run Code Online (Sandbox Code Playgroud)