简体   繁体   English

将 JSON 从 HttpClient 发布到 web API 在 ZD7EFA19FBE7D3972FD4ADB6024Z223D

[英]post JSON from HttpClient to web API in C#

I'm trying to POST a JASON data from HttpClient to my REST API,but it's not working.我正在尝试将 JASON 数据从 HttpClient 发布到我的 REST API,但它不起作用。 the client and the Rest API are not in the same project/solution.客户端和 Rest API 不在同一个项目/解决方案中。

on the HttpClient i'm using the following code:在 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);


    }

the model on the REST API: REST API 上的 model:

public class CustomListItem
{
    public int Id { get; set; }
    public string Text { get; set; }

}

the POST method on REST API: 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);
    }

can you please help?你能帮忙吗?

What Hamlet is referring to is that you are generating JSON like this:哈姆雷特指的是您正在生成 JSON ,如下所示:

{
    agent: {
        Id: 3,
        Text: "Test item3"
    }
}

But your API is expecting just this:但是您的 API 只是期待这个:

{
    Id: 3,
    Text: "Test item3"
}

So you need to change your code to:因此,您需要将代码更改为:

string payload = JsonConvert.SerializeObject(new
    {
        Id = 3,
        Text = "Test item3",
    };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM