gpt4 book ai didi

asp.net-mvc-4 - 从控制台创建 WebAPI 帖子以在 json 数据中包含 $type

转载 作者:行者123 更新时间:2023-12-01 12:43:22 25 4
gpt4 key购买 nike

我正在创建对象并将它们发布到 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
}
]
}

最佳答案

创建了另一个重载使用这个调用来产生正确的请求:

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);
}

关于asp.net-mvc-4 - 从控制台创建 WebAPI 帖子以在 json 数据中包含 $type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22208717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com