【发布时间】:2020-03-18 20:42:35
【问题描述】:
我在一项服务下有多个 API。 API 采用不同的 JSON 有效负载。我想创建一个具有属性和值的模型类并设置它们。这可以通过一个模型类用于多个 API 来实现吗?例如,我有一个 API 方法采用 JSON id 和名称,另一个 API 采用 userID 和颜色。在将请求发送到需要这些数据的特定 API 时,如何指示要应用哪些特定属性和值?我在我的发送请求中使用JsonConvert.SerializeObject(Model)。
目前我的模型中有以下内容。我正在使用 TagModel 类的实例来分配值,但是当使用 SerializeForApiMethod 并说明我需要哪个方法时,它需要分配整个模型值。我正在尝试使用特定方法名称提取我需要的那些。
public class TagModel
{
public static TagModel model = new TagModel
{
endpointIds = new List<int> { -2147483612, -2147483611 },
tagIds = new List<int> { 35, 37 },
id = -2147483639,
parentId = 37
};
[UseWithApiMethods("UpdateEndpointsToTags")]
public List<int> endpointIds { get; set; }
public List<int> tagIds { get; set; }
[UseWithApiMethods("UpdateEndpointsFromTags")]
public int id { get; set; }
public int parentId { get; set; }
}
This is m helper class:
```public class Helper
{
[AttributeUsage(AttributeTargets.Property)]
public class UseWithApiMethodsAttribute : Attribute
{
public UseWithApiMethodsAttribute(params string[] methodNames)
{
MethodNames = methodNames;
}
public string[] MethodNames { get; private set; }
}
public class SelectivePropertyResolver : DefaultContractResolver
{
public string ApiMethodName { get; private set; }
public SelectivePropertyResolver(string apiMethodName)
{
ApiMethodName = apiMethodName;
}
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty prop = base.CreateProperty(member, memberSerialization);
if (member.MemberType == MemberTypes.Property)
{
var att = ((PropertyInfo)member).GetCustomAttribute<UseWithApiMethodsAttribute>(true);
if (att != null && !att.MethodNames.Contains(ApiMethodName))
{
prop.Ignored = true;
}
}
return prop;
}
}
public string SerializeForApiMethod(Object model, string methodName)
{
var settings = new JsonSerializerSettings
{
ContractResolver = new SelectivePropertyResolver(methodName),
Formatting = Formatting.Indented
};
return JsonConvert.SerializeObject(model, settings);
}
}
This is my Method class using the SerializeForApiMethod method
```public HttpWebResponse UpdateEndpointsFromTags()
{
RequestHandler requestor = new RequestHandler(BaseUrl + "UpdateEndpointsFromTags", HttpVerb.POST, AuthenticationType.Bearer);
return requestor.SendRequest(helper.SerializeForApiMethod(model , "UpdateEndpointsFromTags"));
}
public HttpWebResponse UpdateEndpointsToTags()
{
RequestHandler requestor = new RequestHandler(BaseUrl + "UpdateEndpointsToTags", HttpVerb.POST, AuthenticationType.Bearer);
return requestor.SendRequest(helper.SerializeForApiMethod(model, "UpdateEndpointsToTags"));
}
复杂的负载
【问题讨论】:
-
从您的示例看来,API 彼此完全不同。如果是这种情况,我不确定我是否理解通过为他们使用相同的模型可以获得什么。你能详细解释一下你为什么要这样做吗?
-
在框架中,我们有一个模型文件夹,其中包含每个服务的所有模型。例如,我们有一个名为 User 的服务。在用户服务中,我有一个 API 创建了一个用户,另一个 API 更新了一个用户。两者都采用不同的 Json 有效负载。我可以在一个父模型类下创建不同的模型类吗?我试图避免创建这么多模型
标签: c# api testing json.net nunit