[英]post JSON from HttpClient to web API in C#
我正在嘗試將 JASON 數據從 HttpClient 發布到我的 REST API,但它不起作用。 客戶端和 Rest API 不在同一個項目/解決方案中。
在 HttpClient 我使用以下代碼:
private static async void DoIt()
{
string payload = JsonConvert.SerializeObject(new
{
agent = new
{
Id = 3,
Text = "Test item3",
},
});
var client = new HttpClient();
var content = new StringContent(payload, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync("https://localhost:44323/api/listid", content);
}
REST API 上的 model:
public class CustomListItem
{
public int Id { get; set; }
public string Text { get; set; }
}
REST API 上的 POST 方法:
public HttpResponseMessage Post([FromBody] CustomListItem model)
{
if (string.IsNullOrEmpty(model?.Text))
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
var maxId = 0;
if (_listItems.Count > 0)
{
maxId = _listItems.Max(x => x.Id);
}
model.Id = maxId + 1;
_listItems.Add(model);
return Request.CreateResponse(HttpStatusCode.Created, model);
}
你能幫忙嗎?
哈姆雷特指的是您正在生成 JSON ,如下所示:
{
agent: {
Id: 3,
Text: "Test item3"
}
}
但是您的 API 只是期待這個:
{
Id: 3,
Text: "Test item3"
}
因此,您需要將代碼更改為:
string payload = JsonConvert.SerializeObject(new
{
Id = 3,
Text = "Test item3",
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.