Refit 在需要时不会抛出异常

问题描述 投票:0回答:1

改装时遇到奇怪的问题,或者也许我只是错过了一些东西..

我正在测试它并有一个超级基本的设置。我正在尝试进行网络调用,当 Refit 无法反序列化我的模型时,我希望它失败,相反,它只返回空字段,即使它们是必需的。我错过了什么?

我知道 api 返回错误并且 Refit 无法解析模型,但它仍然继续运行..

一些代码:

型号 enter image description here

协议 enter image description here

请求 enter image description here

回应 enter image description here

什么鬼? :D

c# json .net deserialization refit
1个回答
0
投票

使用 Refit 时,将 JSON 响应反序列化到模型中不会自动验证所需属性是否为空。

如果某个属性为 null,即使将其标记为 [Required],Refit 默认情况下也不会抛出错误。相反,您需要在收到响应后显式处理验证。

if(ipAddress is not null)
{
    InternetProtocolDetails ipDetails = await _intenetProptocolApi.GetInfo(ipAddress);
    ValidateModel(ipDetails);
    Console.WriteLine(ipDetails)
}

private void ValidateModel(InternetProtocolDetails model)
{
    if (model.RequiredField == null)
    {
        throw new Exception("Required field is missing in the response.");
    }
    // Add more validation if necessary
}

model.RequiredField 是模型所需的所有属性。

© www.soinside.com 2019 - 2024. All rights reserved.