我正在使用 C# 开发一个 API,用户可以在其中估算该特定计算实例的云成本。
我返回一个类型为
Dictionary<string, Dictionary<string, CloudProduct>>
的字典,其中第一个字符串是“aws”,第二个字符串是“onDemand”、“1Y”、“3Y”和“Storage”。
它看起来像这样:
{
"aws": {
"OnDemand": {
"cpu": 2,
"ram": 4
},
"1Y": {
"cpu": 2,
"ram": 4
},
"3Y": {
"cpu": 2,
"ram": 4
},
"storage": {
"capacity": "200"
}
}
}
在这本词典中,有类
ComputeOffer
和 Storage
。这两个类都继承自类CloudProduct
。
这是返回数据的代码:
[HttpPost]
public JsonResult getRequest(CloudCalculationRequest ccr){
if(ccr.RequestedProviders.Contains("aws")){
foreach(CloudProduct cloudProduct in ccr.CloudProducts){
AWSCaldulator.AddCosts(cloudProduct, ccr.PurchaseOption);
}
}
JsonResult result = new JsonResult(ccr);
return result;
}
使用调试器,我可以看到直到它返回的最后一刻
result
,数据都是正确的并且类被正确识别:
然而,用户收到的一切都是:
"providers": {
"aws": {
"OnDemand": {
"description": "",
"name": "",
"location": "string"
},
"1Y": {
"description": "",
"name": "",
"location": "string"
},
"3Y": {
"description": "",
"name": "",
"location": "string"
},
"storage": {
"description": "",
"name": "",
"location": ""
}
}
这些是
CloudProduct
和 Storage
继承自的 ComputeOffer
类的唯一参数。
我认为这是因为框架需要一个 CloudProduct 实例,然后使用默认值而不是实际数据。
你没有分享什么是
CloudCalculationRequest, CloudProduct, ComputeOffer, Storage and AWSCaldulator.AddCosts
,所以我只能根据我的假设写一个示例。恐怕您对数据类型感到困惑。这是我的代码和测试结果。
[HttpPost("PcCost")]
public JsonResult getRequest(CloudCalculationRequest ccr)
{
var dict = new Dictionary<string, CloudProduct> {
{ "OnDemand", new ComputeOffer{ cpu = "2", ram = "4"} },
{ "1Y", new ComputeOffer{ cpu = "2", ram = "4"} },
{ "3Y", new ComputeOffer{ cpu = "2", ram = "4"} },
{ "storage", new Storage{ capacity = "200"} }
};
var aws = new Dictionary<string, Dictionary<string, CloudProduct>>
{
{ "aws", dict}
};
ccr.aws = aws;
ccr.aws2 = dict;
JsonResult result = new JsonResult(ccr);
return result;
}
public class CloudCalculationRequest {
public string RequestedProviders { get; set; }
public List<CloudProduct> CloudProducts { get; set; }
public Dictionary<string, Dictionary<string, CloudProduct>> aws { get; set; }
public Dictionary<string, CloudProduct> aws2 { get; set; }
}
public class CloudProduct {
public string description { get; set; }
public string name { get; set; }
public string location { get; set; }
}
public class ComputeOffer : CloudProduct {
public string cpu { get; set; }
public string ram { get; set; }
}
public class Storage : CloudProduct
{
public string capacity { get; set; }
}
然后我用输入参数进行测试,例如
{
"RequestedProviders":"aws",
"CloudProducts":[
{
"description": "desc1",
"name": "name1",
"location": "loca1"
},
{
"description": "desc2",
"name": "name2",
"location": "loca2"
}
],
"aws":{},
"aws2":{}
}
我的 API 响应如下图所示。
就像你看到的,如果我们在
public Dictionary<string, Dictionary<string, CloudProduct>> aws { get; set; }
中定义 CloudCalculationRequest
,那么我们就会从 providers
中得到 aws
。如果我们定义 new Dictionary<string, CloudProduct>
但在字典中使用 new ComputeOffer and new Storage
,则 CloudProduct
中的属性也会被返回。