我正在创建对象并将其发布到webapi。基本上我只是无法获取序列化的东西,以便在json中包含$ type信息。以下是我试图编写的代码。之后是我期待的json。
var cds = new List<CreditDefaultSwaps>()
{
new CreditDefaultSwaps() { ModelNumber = "SP8A1ETA", BrokerSpread = 0},
new CreditDefaultSwaps() { ModelNumber = "SP3A0TU1", BrokerSpread = 0},
new CreditDefaultSwaps() { ModelNumber = "SP4A102V", BrokerSpread = 0}
};
var client = new HttpClient {BaseAddress = new Uri("http://localhost/BloombergWebAPI/api/")};
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// set up request object
var oContract = new WebApiDataServiceRequest
{
RequestType = ReferenceDataRequestServiceTypes.ReferenceDataRequest,
SwapType = BloombergWebAPIMarshal.SwapType.CDS,
SecurityList = cds
};
Tried something like this and the var content was formatted as I would expect
however I couldn't post the data using postasjsonasync
//var content = JsonConvert.SerializeObject(oContract, Formatting.Indented,
// new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects });
Console.ReadLine();
var response = client.PostAsJsonAsync("bloombergapi/processbloombergrequest", oContract).Result;
以下是我想发布的json。我在上面的代码中遗漏了什么,我确信这是愚蠢的。
{
"$type": "BloombergWebAPIMarshal.WebApiDataServiceRequest, BloombergWebAPIMarshal",
"RequestType": 3,
"SwapType": 1,
"SecurityList": [
{
"$type": "BloombergWebAPIMarshal.CreditDefaultSwaps, BloombergWebAPIMarshal",
"ModelNumber": "SP8A1ETA",
"BrokerSpread": 0
},
{
"$type": "BloombergWebAPIMarshal.CreditDefaultSwaps, BloombergWebAPIMarshal",
"ModelNumber": "SP3A0TU1",
"BrokerSpread": 0
},
{
"$type": "BloombergWebAPIMarshal.CreditDefaultSwaps, BloombergWebAPIMarshal",
"ModelNumber": "SP4A102V",
"BrokerSpread": 0
}
]
}
答案 0 :(得分:4)
创建另一个重载使用此调用生成正确的请求:
var response = client.PostAsJsonAsync("processbloombergrequest", oContract, TypeNameHandling.Objects).Result
这是新的重载
public static Task<HttpResponseMessage> PostAsJsonAsync<T>(this HttpClient client, string requestUri, T value, TypeNameHandling typeNameHandling)
{
return client.PostAsJsonAsync<T>(requestUri, value, CancellationToken.None, typeNameHandling);
}
public static Task<HttpResponseMessage> PostAsJsonAsync<T>(this HttpClient client, string requestUri, T value, CancellationToken cancellationToken, TypeNameHandling typeNameHandling)
{
var formatter = new JsonMediaTypeFormatter
{
SerializerSettings = new JsonSerializerSettings()
{
TypeNameHandling = typeNameHandling
}
};
return client.PostAsync<T>(requestUri, value, formatter, cancellationToken);
}