我正在尝试将由自定义数据类型组成的列表发送到API控制器内的函数,但无法使其正常工作。
这是我创建的自定义数据类型
public class MinimalStatementModel
{
public int ActivityID { get; set; }
public string StatementCode { get; set; }
public string Value { get; set; }
public string Note { get; set; }
}
这是HttpClient
部分
static async Task UpdateActivityStatement()
{
string uri = "/api/ExtraNet/UpdateActivityStatement";
HttpClient client = new HttpClient();
int ActivityId = 12345; //Aktivite Numarası
string StatementCode = "123456";
string Value = "Test";
string Note = "Test";
string token = ""
client.BaseAddress = "address"
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.Timeout = TimeSpan.FromMinutes(30);
var postData = "{ \"ActivityID\":\"" + ActivityId + "\"" + ","
+"\"StatementCode\":\"" + StatementCode + "\"" + ","
+"\"Value\":\"" + Value + "\"" +","
+"\"Note\":\"" + Note + "\"}";
var content = new StringContent(postData, Encoding.UTF8, "application/json");
HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post, uri);
message.Headers.Add("Authorization", string.Format("bearer {0}", token));
message.Content = content;
HttpResponseMessage response = await client.SendAsync(message);
var responseJson = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseJson);
}
这是API控制器中的部分
public ResponseHelper UpdateActivityStatement(List<MinimalStatementModel> requestList)
{
//releveant codes
}
我能够使用自定义数据类型和HttpClient,但是自定义数据类型的列表花费的时间比我想象的要长。
我如何设法使它起作用?
答案 0 :(得分:1)
您的JSON是单个对象,而不是列表/数组。将对象用方括号(“ []
”括起来代表一个集合。
var postData = "[{ \"ActivityID\":" + ActivityId.ToString() + ","
+"\"StatementCode\":\"" + StatementCode + "\"" + ","
+"\"Value\":\"" + Value + "\"" +","
+"\"Note\":\"" + Note + "\"}]";
答案 1 :(得分:0)
更好的解决方案可能是:
A