REFIT:如何在编写查询时忽略类属性



我有这个问题,我看不到出路:我想改装忽略一些公共属性,而组成一个查询。

假设我有这个类

public class TestClass {
[AliasAs("myprop1")]
public string Prop1 {get; set;}
[AliasAs("myprop2")]
public string Prop2 {get; set;}
public string Prop3 {get; set;}
public string Prop4 {get; set;}
}

和这个接口

public interface IMyClient {
[Get("/login")]
public Task<ApiResponse<TestClass>> Login(string username, string password);
[Get("/verify")]
public Task<ApiResponse<TestClass>> Check(TestClass myClass);
}

当我调用var resp = client.Login("user", "test");API被正确调用时,我得到了所需的结果。
由于这个原因,我需要TestClass的所有属性都是公共的,否则在反序列化响应时,一些属性将被忽略。

接下来,当我调用var resp = client.Verify(resp.Content)时,我只需要将Prop1Prop2传递给API调用。
使Prop3Prop4私有不是一种方法,因为我在调用Login时需要它们。
我已经搜索了一些REFIT属性,但是(我的坏)我找不到任何。

我甚至可以拆分我的类在一个接口只有Prop1Prop2和一个类实现与附加属性的接口,但我希望有一个更简单的解决方案。

是否有办法使用相同的模型?

只需在您不想包含在查询中的属性上方添加属性[JsonIgnore]。根据您拥有的序列化器,它可能来自System.Text.Json(Refit的默认序列化器),也可能来自Newtonsoft.Json

在你的例子中

public class TestClass {
[AliasAs("myprop1")]
public string Prop1 {get; set;}
[AliasAs("myprop2")]
public string Prop2 {get; set;}
[JsonIgnore]
public string Prop3 {get; set;}
[JsonIgnore]
public string Prop4 {get; set;}
}

最新更新