c# - RestSharp 在服务器上抛出 NullReferenceException

标签 c# restsharp

我有一段简单的代码:

try
{
    this.client.ExecuteAsync<Answer>(request, response =>
        {
            if (response.ResponseStatus == ResponseStatus.Completed)
                callback(response.Data);
            ...
        });
}
catch (WebException ex) {...}

并且它在 if 行中抛出 NullReferenceException,因为响应为空。 我该怎么做才能收到有关服务器关闭的消息?

最佳答案

只需为您的响应添加一个空检查:

try
{
    this.client.ExecuteAsync<Answer>(request, response =>
        {
            if (response != null && response.ResponseStatus == ResponseStatus.Completed)
                callback(response.Data);
            else
            {
               // add logic here to handle bad case
            }
        });
}
catch (WebException ex) {...}

关于c# - RestSharp 在服务器上抛出 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21910973/

相关文章:

c# - 如何在 C# 中使用 RestSharp 反序列化动态 json 属性?

ios - 仅设备上的 RestSharp/MonoTouch 错误

c# - 为什么我的代码会泄漏连接?

c# - 添加属性以在 Entity Framework Core 中配置小数精度

c# - 单元测试异步方法 : The remote hostanme could not be resolved

c# - 使用 C# 使用 Azure DevOps Rest API 创建工作项

json - 使用数组反序列化 json 对象失败,未找到类型 System.String[] 的默认构造函数

c# - RESTSharp 在反序列化包括字节顺序标记的 XML 时遇到问题?

c# - 如何使 Entity Framework 6 (DB First) 显式插入 Guid/UniqueIdentifier 主键?

c# - 是否 (HttpContext.Current.User != null) 足以假设 FormsAuthentication 已对用户进行身份验证