如何在c# HttpClient中使用Get发送复杂对象



我有一个c#项目,希望利用一个api。如果感兴趣,文档在这里:link

当我想要一个所有"客户"的列表时;来自api,它有一些必需的属性:

的注意。自我、货币、客户联系方式。自我,customerGroup,customerGroup。自我,defaultDeliveryLocation。自我,invoices.self,布局。self, name, paymentTerms, paymentTerms。自我,salesPerson.self,自我,模板。自我,总数。self, vatZone, vatZone.self

我有一个自定义对象,其命名与所需属性相同。对象很复杂,因为它引用了诸如"attention"、"customerContact"、"customerGroup"、"paymentTerms"等对象。如文档所述。

现在我必须使用的端点是"customers",所以我必须参数化属性。

我已经寻找了一个解决方案,将一个复杂的对象转换成一个uri"?name=Mike&currency=USD&…",但不幸的是,我只找到了一个解决方案,可以使一个自定义对象只有简单的类型格式化参数字符串。

所以我放弃了,并尝试编写自己的硬编码url字符串,但是我如何将复杂的对象放入url查询中,比如"attention.self"?

">

? attention.self = Something& . ."让API翻译它,这样它就知道"注意"了。是另一个对象和"自我"那上面有属性吗?

任何关于如何做这个更优化的建议将是伟大的。

您可以使用Reflection:

public IEnumerable<string> ToQueryStringItem<T>(T entity)
{
foreach(var pi in typeof(T).GetProperties())
yield return $"{pi.Name}={pi.GetValue(entity)}";
}
public IEnumerable<string> ToQueryString<T>(T entity)
=> $"?{string.Join("&", ToQueryString(entity).ToList())}";

现在你可以这样做:

string qs = ToQueryString(someClassInstance);

请注意,如果类属性不是基本类型,则需要更复杂的代码来进行反射。

如果你想要一些自定义的值,它也是可行的,例如我们说,不是truefalse,你想要10:

foreach(var pi in typeof(T).GetProperties())
{
switch(pi.PropertyType.ToString())
{
case "Boolean":
yield return $"{pi.Name}={(pi.GetValue(entity)?1:0)};
//....
default:
yield return $"{pi.Name}={pi.GetValue(entity)}";   
}
}

您可能还想隐藏一些属性,以避免在查询字符串中使用,为此您可以创建一个属性:

public class IgnoreInQueryStringAttribute: Attribute {}

,并将其用于查询字符串中不希望出现的任何属性:

public class Customer
{
[IgnoreInQueryString]
public int Id { get; set; }
public string Firstname { get; set; } 
}

然后:

foreach(var pi in typeof(T).GetProperties())
{
if(pi.GetCustomAttributes(typeof(IgnoreInQueryString), false).Length == 0)     
{
//....
}
}

最新更新