Send HTTP POST message in ASP.NET Core using HttpClient PostAsJsonAsync

后端 未结 5 1601
灰色年华
灰色年华 2020-11-27 14:20

I want to send dynamic object like

new { x = 1, y = 2 };

as body of HTTP POST message. So I try to write

var client = new H         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 14:31

    I use this class:

    public class JsonContent : StringContent
    {
        public JsonContent(object obj) :
            base(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json")
        { }
    }
    

    Sample of usage:

    new HttpClient().PostAsync("http://...", new JsonContent(new { x = 1, y = 2 }));
    

提交回复
热议问题