簡體   English   中英

使用Httpclient將數據發布到參數不復雜的WebApi object

[英]Post data to the WebApi which its parameter is not complex object using Httpclient

這是我的 webapi 發布請求

    [HttpPost]
    [Route("Create/{id}")]
    public async Task<IActionResult> CreateContact(Guid id, string email, string fullName)
    {
        // code removed for brevity
    }

如何將contact object 發布到 webapi? 這就是我在客戶端中所擁有的。

   using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://localhost:123");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var contact = new Contact() { Id = 12345, Email = "test@gmail.com", FullName = "John" };
            HttpResponseMessage response = await client.PostAsJsonAsync($"/api/Contact/Create/{contact.Id}", contact);

            if (response.IsSuccessStatusCode)
            {
                
            }
            else
            {
         
            }
        }

不確定這是否是最好的,但它有效。 Route屬性中添加更多參數

[HttpPost]
[Route("Create/{id}/{email}/{fullName}")]
public async Task<IActionResult> CreateContact(Guid id, string email, string fullName)
{
    // code removed for brevity
}

然后在 httpclient

 HttpResponseMessage response = await client.PostAsJsonAsync($"/api/Contact/Create/{contact.Id}/{contact.Email}/{contact.FullName}", contact);

您好在您的 WPI 中使用 [FromBody]。 您可以將聯系人發布為 object

    [HttpPost]
    [Route("Create/{contact}")]
    public async Task<IActionResult> CreateContact([FromBody]Contact contact)
    {
        // code removed for brevity
    }
   using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://localhost:123");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var contact = new Contact() { Id = 12345, Email = "test@gmail.com", FullName = "John" };
            var contactJson = JsonConvert.SerializeObject(contact);
            var stringContent = new StringContent(contactJson , UnicodeEncoding.UTF8, "application/json");

            HttpResponseMessage response = await client.PostAsync($"/api/Contact/Create/", stringContent);

            if (response.IsSuccessStatusCode)
            {
                
            }
            else
            {
         
            }
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM